jhtp7LM 13
jhtp7LM 13
Exception
It is common sense to take a
Handling
method and try it. If it fails,
admit it frankly and try
another. But above all, try
something.
—Franklin Delano Roosevelt
O! throw away the worser
part of it,
And live the purer with the OBJECTIVES
other half. In this chapter you will learn:
—William Shakespeare
If they’re running and they ■ How exception and error handling works.
don’t look where they’re going ■ To use try, throw and catch to detect, indicate and
I have to come out from
somewhere and catch them.
handle exceptions, respectively.
—Jerome David Salinger ■ To use the finally block to release resources.
O infinite virtue! com’st thou ■ How stack unwinding enables exceptions not caught in
smiling from the world’s one scope to be caught in another scope.
great snare uncaught?
—William Shakespeare ■ How stack traces help in debugging.
■ How exceptions are arranged in an exception class
hierarchy.
■ To declare new exception classes.
■ To create chained exceptions that maintain complete
stack trace information.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 425
Assignment Checklist
Name: Date:
Section:
Prelab Activities
Matching YES NO
Fill in the Blank 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24
Short Answer 25, 26, 27, 28, 29, 30, 31, 32
Programming Output 33, 34, 35, 36
Correct the Code 37, 38, 39
Lab Exercises
Exercise — Access Array YES NO
Follow-Up Question and Activity 1
Debugging YES NO
Labs Provided by Instructor
1.
2.
3.
Postlab Activities
Coding Exercises 1, 2
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 427
Prelab Activities
Matching
Name: Date:
Section:
After reading Chapter 13 of Java How to Program: Seventh Edition, answer the given questions. These questions
are intended to test and reinforce your understanding of key Java concepts. You may answer these questions ei-
ther before or during the lab.
For each term in the column on the left, write the corresponding letter for the description that best matches it
from the column on the right.
Term Description
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 429
Name: Date:
Section:
13. A(n) is an indication that a problem occurred during the program’s execution.
16. If no exception handler matches a particular thrown object, the search for a match continues with the ex-
ception handlers of an enclosing .
17. Once an exception is thrown, program control cannot return directly to the .
18. A catch clause for type can handle exceptions of any type.
19. A catch clause for type can catch any object that can be used with the exception-handling mech-
anism.
20. A(n) always executes as long as program control enters its corresponding try block.
24. A(n) must be true when a method is invoked and a(n) must be true after a method suc-
cessfully returns.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 431
Short Answer
Short Answer
Name: Date:
Section:
In the space provided, answer each of the given questions. Your answers should be concise; aim for two or three
sentences.
26. What is the difference between the termination model of exception handling, used in Java, and the resump-
tion model of exception handling?
27. Describe the general flow of control through a try…catch…finally when an exception occurs and is
caught.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
432 Exception Handling Chapter13
Short Answer
28. Describe the general flow of control through a try…catch…finally when an exception occurs and is not
caught. What happens to the exception object that was thrown?
29. Explain the restrictions on the throws clause of a subclass method that overrides a superclass method.
30. Explain the “catch or declare” requirement of Java exception handling. How does this affect exception types
that are direct or indirect subclasses of RuntimeException?
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 433
Short Answer
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 435
Programming Output
Programming Output
Name: Date:
Section:
For each of the given program segments, read the code and write the output in the space provided below each
program. [Note: Do not execute these programs on a computer.]
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
436 Exception Handling Chapter13
Programming Output
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 437
Programming Output
Your answer:
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
438 Exception Handling Chapter13
Programming Output
36. What is output by the following program if the user enters the values 3 and 4.7?
1 import javax.swing.JOptionPane;
2
3 public class Test
4 {
5 public static String sum( int num1, int num2 )
6 {
7 return String.format( "%d + %d = %d", num1, num2, ( num1 + num2 ) );
8 }
9
10 public static void main( String args[] )
11 {
12 int number1;
13 int number2;
14
15 try
16 {
17 number1 =
18 Integer.parseInt( JOptionPane.showInputDialog( "Enter an integer: " ) );
19
20 number2 = Integer.parseInt(
21 JOptionPane.showInputDialog( "Enter another integer: " ) );
22
23 System.out.println( sum( number1, number2 ) );
24 }
25 catch ( NumberFormatException numberFormatException )
26 {
27 System.out.println( numberFormatException.toString() );
28 }
29 } // end main method
30 } // end class Test
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 439
Name: Date:
Section:
Determine if there is an error in each of the following program segments. If there is an error, specify whether it
is a logic error or a compilation error, circle the error in the program and write the corrected code in the space
provided after each problem. If the code does not contain an error, write “no error.” [Note: There may be more
than one error in each program segment.]
37. The following code segment should catch only NumberFormatExceptions and display an error message di-
alog if such an exception occurs:
Your answer:
38. In the following code segment, assume that method1 can throw both NumberFormatExceptions and
ArithmeticExceptions. The following code segment should provide appropriate exception handlers for
each exception type and should display an appropriate error message dialog in each case:
1 try
2 method1();
3
4 catch ( NumberFormatException n, ArithmeticException a )
5 {
6 JOptionPane.showMessageDialog( this,
7 String.format( "The following exception occurred\n%s\n%s\n",
8 n.toString(), a.toSting() ),
9 "Exception occurred", JOptionPane.ERROR_MESSAGE );
10 }
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
440 Exception Handling Chapter13
Your answer:
39. The following code segment should display an error message dialog if the user does not enter two integers:
1 try
2 {
3 int number1 =
4 Integer.parseInt( JOptionPane.showInputDialog( "Enter first integer:" ) );
5 int number2 =
6 Integer.parseInt( JOptionPane.showInputDialog( "Enter second integer:" ) );
7
8 JOptionPane.showMessageDialog( this, "The sum is: " + ( number1 + number2 ) );
9 }
Your answer:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 441
Lab Exercises
Lab Exercise — Access Array
Name: Date:
Section:
The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. Description of the Problem
3. Sample Output
4. Program Template (Fig. L 13.1–Fig. L 13.3)
5. Problem-Solving Tips
6. Follow-Up Question and Activity
The program template represents a complete working Java program with one or more key lines of code replaced
with comments. Read the problem description and examine the sample output, then study the template code.
Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the
program. Compare your output with the sample output provided. Then answer the follow-up question. The
source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.
Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 13 of Java How to Program: Seventh Edi-
tion. In this lab, you will practice:
• Using exception handling to determine valid inputs.
• Using exception handling to write more robust and more fault-tolerant programs.
The follow-up question and activity also will give you practice:
• Creating your own exception type and throwing exceptions of that type.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
442 Exception Handling Chapter13
Sample Output
Program Template
1 // NumberNotFoundException.java
2 public class NumberNotFoundException extends Exception
3 {
4 // no-argument constructor specifies default error message
5 public NumberNotFoundException()
6 {
7 super( "Number not found in array" );
8 }
9
10 // constructor to allow customized error message
11 public NumberNotFoundException( String message )
12 {
13 super( message );
14 }
15 } // end class NumberNotFoundException
1 // ArrayAccess.java
2 import java.awt.FlowLayout;
3 import java.awt.GridLayout;
4 import java.awt.event.ActionEvent;
5 import java.awt.event.ActionListener;
6 import javax.swing.JFrame;
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 443
7 import javax.swing.JLabel;
8 import javax.swing.JOptionPane;
9 import javax.swing.JPanel;
10 import javax.swing.JTextField;
11
12 public class ArrayAccess extends JFrame
13 {
14 private JTextField inputField;
15 private JTextField retrieveField1;
16 private JTextField retrieveField2;
17 private JTextField outputField;
18 private JPanel inputArea;
19 private JPanel retrieveArea;
20 private JPanel outputArea;
21
22 private int num;
23 private int index = 0;
24 private int array[] = new int[ 10 ];
25 private String result;
26
27 // set up GUI
28 public ArrayAccess()
29 {
30 super( "Accessing Array values" );
31 setLayout( new FlowLayout() );
32
33 // set up input Panel
34 inputArea = new JPanel();
35 inputArea.add( new JLabel( "Enter array elements here" ) );
36 inputField = new JTextField( 10 );
37 inputArea.add( inputField );
38 inputField.addActionListener(
39 new ActionListener()
40 {
41 public void actionPerformed( ActionEvent e )
42 {
43 /* Create a try block in which the application reads the number
44 entered in the inputField and assigns it to the next index
45 in the array, then increments instance variable index. */
46
47 /* Write catch handlers that catch the two types of exceptions
48 that the previous try block might throw (NumberFormatException
49 and ArrayIndexOutOfBoundsException), and display appropriate
50 messages in error message dialogs. */
51
52 inputField.setText( "" );
53 } // end method actionPerformed
54 } // end anonymous inner class
55 ); // end call to addActionListener
56
57 // set up retrieve Panel
58 retrieveArea = new JPanel( new GridLayout( 2, 2 ) );
59 retrieveArea.add( new JLabel( "Enter number to retrieve" ) );
60 retrieveField1 = new JTextField( 10 );
61 retrieveArea.add( retrieveField1 );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
444 Exception Handling Chapter13
62 retrieveField1.addActionListener(
63 new ActionListener()
64 {
65 public void actionPerformed( ActionEvent event )
66 {
67 /* Create a try block in which the application reads from
68 retrieveField1 the number the user wants to find in the
69 array, then searches the current array contents for the number.
70 If the number is found, the outputField should display all the
71 indices in which the number was found. If the number is not
72 found, a NumberNotFoundException should be thrown. */
73
74 /* Write catch handlers that catch the two types of exceptions that
75 the try block might throw (NumberFormatException and
76 NumberNotFoundException), and display appropriate messages
77 in error message dialogs. */
78
79 retrieveField1.setText( "" );
80 } // end method actionPerformed
81 } // end anonymous inner class
82 ); // end call to addActionListener
83
84 retrieveArea.add( new JLabel( "Enter index to retrieve" ) );
85 retrieveField2 = new JTextField( 10 );
86 retrieveArea.add( retrieveField2 );
87 retrieveField2.addActionListener(
88 new ActionListener()
89 {
90 public void actionPerformed( ActionEvent event )
91 {
92 /* Create a try block in which the application reads from
93 retrieveField2 the index of a value in the array, then
94 displays the value at that index in the outputField. If the index
95 input by the user is not a number a NumberFormatException should
96 be thrown. If the number input by the user is outside the array
97 bounds or represents an element in which the application has not
98 stored a value, an ArrayIndexOutOfBoundsException should
99 be thrown. */
100
101 /* Write catch handlers that catch the two types of exceptions
102 the try block might throw (NumberFormatException and
103 ArrayIndexOutOfBoundsException), and display appropriate
104 messages in error message dialogs. */
105
106 retrieveField2.setText( "" );
107 } // end anonymous inner class
108 } // end new ActionListener
109 ); // end call to addActionListener
110
111 // set up output Panel
112 outputArea = new JPanel();
113 outputArea.add( new JLabel( "Result" ) );
114 outputField = new JTextField( 30 );
115 outputField.setEditable( false );
116 outputArea.add( outputField );
117
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 445
1 // ArrayAccessTest.java
2 import javax.swing.JFrame;
3
4 public class ArrayAccessTest
5 {
6 // execute application
7 public static void main( String args[] )
8 {
9 ArrayAccess application = new ArrayAccess();
10 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11 application.setSize( 400, 200 );
12 application.setVisible( true );
13 }
14 } // end class ArrayAccessTest
Problem-Solving Tips
1. When you search the array for a value, you should define a boolean value at the beginning of the try
block and initialize it to false. If the value is found in the array, set the boolean value to true. This
will help you determine whether you need to throw an exception due to a search key that is not found.
2. Refer to the sample output to decide what messages to display in the error dialogs.
3. Each of the three event handlers will have its own try statement.
4. If you have any questions as you proceed, ask your lab instructor for assistance.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 447
Debugging
Debugging
Name: Date:
Section:
The program in this section does not compile. Fix all the syntax errors, so that the program will compile success-
fully. Once the program compiles, execute the program, and compare the output with the sample output. Then
eliminate any logic errors that may exist. The sample output demonstrates what the program’s output should be
once the program’s code is corrected. The source code is available at the Web sites www.deitel.com/books/
jhtp7/ and www.prenhall.com/deitel.
Sample Output
Broken Code
1 import java.io.IOException;
2
3 public class SpecialIOException throws IOException
4 {
5 public SpecialIOException()
6 {
7 super( "Special IO Exception Occurred" );
8 }
9
10 public SpecialIOException( String message )
11 {
12 this( message );
13 }
14 } // end class SpecialIOException
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
448 Exception Handling Chapter13
Debugging
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 449
Postlab Activities
Coding Exercises
Name: Date:
Section:
These coding exercises reinforce the lessons learned in the lab and provide additional programming experience
outside the classroom and laboratory environment. They serve as a review after you have successfully completed
the Prelab Activities and Lab Exercises.
For each of the following problems, write a program or a program segment that performs the specified action:
1. Define a class InvalidInputException. This class should be a direct subclass of Exception. It should specify
the default message "Your input was invalid.", but should also enable the programmer to specify a custom
message as well.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.