IM Jhtp7 Ch13
IM Jhtp7 Ch13
IM Jhtp7 Ch13
Exception
Handling
It is common sense to take a
method and try it. If it fails,
admit it frankly and try
another. But above all, try
something.
—Franklin Delano Roosevelt OBJECTIVES
O! throw away the worser In this chapter you will learn:
part of it,
And live the purer with the
■ How exception and error handling works.
other half. ■ To use try, throw and catch to detect, indicate and
—William Shakespeare handle exceptions, respectively.
If they’re running and they ■ To use the finally block to release resources.
don’t look where they’re going ■ How stack unwinding enables exceptions not caught in
I have to come out from one scope to be caught in another scope.
somewhere and catch them.
—Jerome David Salinger ■ How stack traces help in debugging.
O infinite virtue! com’st thou ■ How exceptions are arranged in an exception-class
smiling from the world’s hierarchy.
great snare uncaught? ■ To declare new exception classes.
—William Shakespeare
■ To create chained exceptions that maintain complete
stack-trace information.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
2 Chapter 13 Exception Handling
Self-Review Exercises
13.1 List five common examples of exceptions.
ANS: Memory exhaustion, array index out of bounds, arithmetic overflow, division by ze-
ro, invalid method parameters.
13.2 Give several reasons why exception-handling techniques should not be used for conven-
tional program control.
ANS: (a) Exception handling is designed to handle infrequently occurring situations that
often result in program termination, not situations that arise all the time. (b) Flow of
control with conventional control structures is generally clearer and more efficient
than with exceptions. (c) The “additional” exceptions can get in the way of genuine
error-type exceptions. It becomes more difficult for the programmer to keep track of
the larger number of exception cases.
13.3 Why are exceptions particularly appropriate for dealing with errors produced by methods
of classes in the Java API?
ANS: It is unlikely that methods of classes in the Java API could perform error processing
that would meet the unique needs of all users.
13.4 What is a “resource leak”?
ANS: A “resource leak” occurs when an executing program does not properly release a re-
source when it is no longer needed, thus preventing the resource from being reused.
13.5 If no exceptions are thrown in a try block, where does control proceed to, when the try
block completes execution?
ANS: The catch blocks for that try statement are skipped, and the program resumes exe-
cution after the last catch block. If there is a finally block, it is executed first; then
the program resumes execution after the finally block.
13.6 Give a key advantage of using catch( Exception exceptionName ).
ANS: The form catch( Exception exceptionName ) catches any type of exception thrown
in a try block. An advantage is that no thrown Exception can slip by without being
caught. The programmer can then decide to handle the exception or possibly rethrow
it.
13.7 Should a conventional application catch Error objects? Explain.
ANS: Errors are usually serious problems with the underlying Java system; most programs
will not want to catch Errors because the program will not be able to recover from
such problems.
13.8 What happens if no catch block matches the type of a thrown object?
ANS: This causes the search for a match to continue in the next enclosing try statement.
If there is a finally block, it will be executed before the exception goes to the next
enclosing try statement. If there are no enclosing try statements for which there are
matching catch blocks, and the exception is checked, a compilation error occurs. If
there are no enclosing try statements for which there are matching catch blocks and
the exception is unchecked, a stack trace is printed and the current thread terminates
early.
13.9 What happens if several catch blocks match the type of the thrown object?
ANS: The first matching catch block after the try block is executed.
13.10 Why would a programmer specify a superclass type as the type in a catch block?
ANS: This enables a program to catch related types of exceptions and process them in a uni-
form manner. However, it is often useful to process the subclass types individually
for more precise exception handling.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 3
Exercises
13.15 List the various exceptional conditions that have occurred in programs throughout this text
so far. List as many additional exceptional conditions as you can. For each of these, describe briefly
how a program typically would handle the exception by using the exception-handling techniques
discussed in this chapter. Some typical exceptions are division by zero, arithmetic overflow, and ar-
ray index out of bounds.
ANS: A few examples are: Division by zero - catch the exception, inform user of the attempt
to divide by zero. Array subscript out of bounds - catch the exception and print an
error message telling the user what index was being referenced incorrectly, and exit
the program in a controlled manner. Bad cast - catch the exception and either cast it
to the proper type if that can be determined, or print an error message indicating
what the bad cast was, and exit the program. Invalid input - catch the exception and
inform the user that the input cannot be converted to the proper type.
13.16 Until this chapter, we have found dealing with errors detected by constructors to be a bit
awkward. Explain why exception handling is an effective means for dealing with constructor failure.
ANS: A thrown exception passes to the outside world the information about the failed con-
structor and the responsibility to deal with the failure. Exceptions thrown in con-
structors cause objects built as part of the object being constructed to be marked for
eventual garbage collection.
13.17 (Catching Exceptions with Superclasses) Use inheritance to create an exception superclass
(called ExceptionA) and exception subclasses ExceptionB and ExceptionC, where ExceptionB inher-
its from ExceptionA and ExceptionC inherits from ExceptionB. Write a program to demonstrate
that the catch block for type ExceptionA catches exceptions of types ExceptionB and ExceptionC.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
4 Chapter 13 Exception Handling
8 {
9 try // throw ExceptionC
10 {
11 throw new ExceptionC();
12 } // end try
13 catch ( ExceptionA exception1 ) // catch ExceptionA and subclasses
14 {
15 System.err.println( "First Exception subclass caught. \n" );
16 } // end catch
17
18 try // throw ExceptionB
19 {
20 throw new ExceptionB();
21 } // end try
22 catch ( ExceptionA exception2 ) // catch ExceptionA and subclasses
23 {
24 System.err.println( "Second Exception subclass caught. \n" );
25 } // end try
26 } // end main
27 } // end class Demo
28
29 // exception subclasses
30 class ExceptionA extends Exception
31 {
32 // empty class body
33 } // end class ExceptionA
34
35 class ExceptionB extends ExceptionA
36 {
37 // empty class body
38 } // end class ExceptionB
39
40 class ExceptionC extends ExceptionB
41 {
42 // empty class body
43 } // end class ExceptionC
13.18 (Catching Exceptions Using Class Exception) Write a program that demonstrates how vari-
ous exceptions are caught with
This time, define classes ExceptionA (which inherits from class Exception) and ExceptionB (which
inherits from class ExceptionA). In your program, create try blocks that throw exceptions of types
ExceptionA, ExceptionB, NullPointerException and IOException. All exceptions should be
caught with catch blocks specifying type Exception.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 5
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6 Chapter 13 Exception Handling
53
54 // subclass of ExceptionA
55 class ExceptionB extends ExceptionA
56 {
57 // empty class body
58 } // end class ExceptionB
ExceptionA
ExceptionB
java.lang.NullPointerException
java.io.IOException
13.19 (Order of catch Blocks) Write a program that shows that the order of catch blocks is impor-
tant. If you try to catch a superclass exception type before a subclass type, the compiler should gen-
erate errors.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 7
13.20 (Constructor Failure) Write a program that shows a constructor passing information about
constructor failure to an exception handler. Define class SomeException, which throws an Excep-
tion in the constructor. Your program should try to create an object of type SomeException and
catch the exception that is thrown from the constructor.
ANS:
java.lang.Exception
13.21 (Rethrowing Exceptions) Write a program that illustrates rethrowing an exception. Define
methods someMethod and someMethod2. Method someMethod2 should initially throw an exception.
Method someMethod should call someMethod2, catch the exception and rethrow it. Call someMethod
from method main, and catch the rethrown exception. Print the stack trace of this exception.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
8 Chapter 13 Exception Handling
13.22 (Catching Exceptions Using Outer Scopes) Write a program showing that a method with its
own try block does not have to catch every possible error generated within the try. Some exceptions
can slip through to, and be handled in, other scopes.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 9
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.