0% found this document useful (0 votes)
78 views21 pages

jhtp7LM 13

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views21 pages

jhtp7LM 13

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

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:

Exercises Assigned: Circle assignments Date Due

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

1. try block a) Keyword that initiates an exception.


2. finally block b) Displays the method-call stack at the time that an exception oc-
3. Exception
curred.
4. catch
c) Thrown when a program attempts to divide by zero in integer
arithmetic.
5. throw
d) Contains code that may generate exceptions.
6. ArithmeticException
e) Superclass from which all exceptions are derived.
7. NumberFormatException
f) Serious problem from which most programs cannot recover.
8. printStackTrace
g) Exception that can occur at any point during the execution of
9. stack unwinding the program and can usually be avoided by coding properly.
10. getStackTrace h) Method that returns an array of StackTraceElements.
11. RuntimeException i) Keyword that begins the declaration of an exception handler.
12. Error j) The process by which an exception that is not caught is re-
turned to a calling method in an attempt to locate an appropri-
ate exception handler.
k) Occurs when an attempt is made to convert a String to a nu-
meric value and the String does not represent a number.
l) Typically, contains code that releases resources allocated in its
corresponding try block.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 429

Prelab Activities Name:

Fill in the Blank

Fill in the Blank

Name: Date:

Section:

Fill in the blanks for each of the following statements:

13. A(n) is an indication that a problem occurred during the program’s execution.

14. Each specifies the type of exception it can handle.

15. Only objects can be used with the exception-handling mechanism.

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.

21. A(n) lists the exceptions that a method might throw.

22. Class Throwable has two subclasses— and .

23. There are two categories of exceptions in Java— and .

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

Prelab Activities Name:

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.

25. Explain when exception handling should be used.

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

Prelab Activities Name:

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?

31. Why would a catch block rethrow an exception?

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 433

Prelab Activities Name:

Short Answer

32. Explain the process of stack unwinding

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 435

Prelab Activities Name:

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.]

33. What is output by the following application?

1 public class Test


2 {
3 public static String lessThan100( int number ) throws Exception
4 {
5 if ( number >= 100 )
6 throw new Exception( "Number too large." );
7
8 return String.format( "The number %d is less than 100", number );
9 }
10
11 public static void main( String args[] )
12 {
13 try
14 {
15 System.out.println( lessThan100( 1 ) );
16 System.out.println( lessThan100( 22 ) );
17 System.out.println( lessThan100( 100 ) );
18 System.out.println( lessThan100( 11 ) );
19 }
20 catch( Exception exception )
21 {
22 System.out.println( exception.toString() );
23 }
24 } // end main method
25 } // end class Test

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
436 Exception Handling Chapter13

Prelab Activities Name:

Programming Output

34. What is output by the following program?

1 public class Test


2 {
3 public static void method3() throws RuntimeException
4 {
5 throw new RuntimeException( "RuntimeException occurred in method3" );
6 }
7
8 public static void method2() throws RuntimeException
9 {
10 try
11 {
12 method3();
13 }
14 catch ( RuntimeException exception )
15 {
16 System.out.printf( "The following exception occurred in method2\n%s\n",
17 exception.toString() );
18 throw exception;
19 }
20 } // end method2
21
22 public static void method1() throws RuntimeException
23 {
24 try
25 {
26 method2();
27 }
28 catch ( RuntimeException exception )
29 {
30 System.out.printf( "The following exception occurred in method1\n%s\n",
31 exception.toString() );
32 throw exception;
33 }
34 } // end method1
35
36 public static void main( String args[] )
37 {
38 try
39 {
40 method1();
41 }
42 catch ( RuntimeException exception )
43 {
44 System.out.printf( "The following exception occurred in main\n%s\n",
45 exception.toString() );
46 }
47 } // end main
48 } // end class test

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 437

Prelab Activities Name:

Programming Output

Your answer:

35. What is output by the following program?

1 public class Test


2 {
3 public static String divide( int number1, int number2 )
4 {
5 return String.format( "%d divided by %d is %d",
6 number1, number2, ( number1 / number2 ) );
7 }
8
9 public static void main( String args[] )
10 {
11 try
12 {
13 System.out.println( divide( 4, 2 ) );
14 System.out.println( divide( 20, 5 ) );
15 System.out.println( divide( 100, 0 ) );
16 }
17 catch( Exception exception )
18 {
19 System.out.println( exception.toString() );
20 }
21 } // end main
22 } // end class Test

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
438 Exception Handling Chapter13

Prelab Activities Name:

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

Prelab Activities Name:

Correct the Code

Correct the Code

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:

1 catch ( Exception exception )


2 JOptionPane.showMessageDialog( this,
3 "A number format exception has occurred",
4 "Invalid Number Format", JOptionPane.ERROR_MESSAGE );

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

Prelab Activities Name:

Correct the Code

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.

Description of the Problem


Write a program that allows a user to input integer values into a 10-element array and search the array. The pro-
gram should allow the user to retrieve values from the array by index or by specifying a value to locate. The pro-
gram should handle any exceptions that might arise when inputting values or accessing array elements. The
program should throw a NumberNotFoundException (Fig. L 13.1) if a particular value cannot be found in the
array during a search. If an attempt is made to access an element outside the array bounds, catch the ArrayIn-
dexOutOfBoundsException and display an appropriate error message. Also, the program should throw an Array-
IndexOutOfBoundsException if an attempt is made to access an element for which the user has not yet input a
value.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
442 Exception Handling Chapter13

Lab Exercises Name:

Lab Exercise — Access Array

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

Fig. L 13.1 | NumberNotFoundException.java.

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;

Fig. L 13.2 | ArrayAccess.java. (Part 1 of 4.)

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 443

Lab Exercises Name:

Lab Exercise — Access Array

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 );

Fig. L 13.2 | ArrayAccess.java. (Part 2 of 4.)

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
444 Exception Handling Chapter13

Lab Exercises Name:

Lab Exercise — Access Array

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

Fig. L 13.2 | ArrayAccess.java. (Part 3 of 4.)

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 445

Lab Exercises Name:

Lab Exercise — Access Array

118 add( inputArea );


119 add( retrieveArea );
120 add( outputArea );
121 } // end constructor
122 } // end class ArrayAccess

Fig. L 13.2 | ArrayAccess.java. (Part 4 of 4.)

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

Fig. L 13.3 | ArrayAccessTest.java.

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.

Follow-Up Question and Activity


1. Create another exception class called DuplicateValueException that will be thrown if the user inputs a val-
ue that already resides in the array. Modify your lab exercise solution to use this new exception class to in-
dicate when a duplicate value is input, in which case an an appropriate error message should be displayed.
The program should continue normal execution after handling the exception.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 13 Exception Handling 447

Lab Exercises Name:

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

SpecialIOException: Special IO Exception Occurred

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

1 // Debugging Chapter 13: DebugException.java


2 import java.io.IOException;
3
4 public class DebugException
5 {
6 public static void main( String args[] )
7 {
8 try
9 {
10 throw new SpecialIOException();
11 }
12 catch ( Exception exception )
13 {
14 System.err.println( exception.toString() );
15 }

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
448 Exception Handling Chapter13

Lab Exercises Name:

Debugging

16 catch ( IOException ioException )


17 {
18 System.err.println( ioException.toString() );
19 }
20 catch ( SpecialIOException specialIOException )
21 {
22 specialIOException.toString();
23 }
24 } // end method main
25 } // end class DebugException

© 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.

2. Define a class ExceptionTest based on class DivideByZeroWithExceptionHandling of Fig. 13.2 of Java


How To Program: Seventh Edition. Not only should ExceptionTest check for division by zero and valid in-
teger input, it should also ensure that the integers being input are positive. If they are not, it should throw
an InvalidInputException (using the class from Coding Exercise 1) with the message "You must enter pos-
itive numbers". The program should catch this exception and display an error message.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy