You are on page 1of 9

13

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

13.11 What is the key reason for using finally blocks?


ANS: The finally block is the preferred means for releasing resources to prevent resource
leaks.
13.12 What happens when a catch block throws an Exception?
ANS: First, control passes to the finally block if there is one. Then the exception will be
processed by a catch block (if one exists) associated with an enclosing try block (if
one exists).
13.13 What does the statement throw exceptionReference do?
ANS: It rethrows the exception for processing by an exception handler of an enclosing try
statement, after the finally block of the current try statement executes.
13.14 What happens to a local variable in a try block when that block throws an Exception?
ANS: The variable goes out of scope, and the reference count for any object it referenced is
decremented. If the reference count becomes zero, the object is marked for garbage
collection.

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:

1 // Exercise 13.17 Solution: Demo.java


2 // Program demonstrates that the exception
3 // superclass will catch the subclass exceptions.
4
5 public class Demo
6 {
7 public static void main( String args[] )

© 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

First Exception subclass caught.

Second Exception subclass caught.

13.18 (Catching Exceptions Using Class Exception) Write a program that demonstrates how vari-
ous exceptions are caught with

catch ( Exception exception )

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

1 // Exercise 13.18 Solution: Demo2.java


2 // Program demonstrates catching Exception exception.
3 import java.io.IOException;
4
5 public class Demo2
6 {
7 // execute application
8 public static void main( String args[] )
9 {
10 try
11 {
12 throw new ExceptionA();
13 } // end try
14 catch ( Exception exception )
15 {
16 System.out.println( exception.toString() );
17 } // end catch
18
19 try
20 {
21 throw new ExceptionB();
22 } // end try
23 catch ( Exception exception )
24 {
25 System.out.println( exception.toString() );
26 } // end try
27
28 try
29 {
30 throw new NullPointerException();
31 } // end try
32 catch ( Exception exception )
33 {
34 System.out.println( exception.toString() );
35 } // end catch
36
37 try
38 {
39 throw new IOException();
40 } // end try
41 catch ( Exception exception )
42 {
43 System.out.println( exception.toString() );
44 } // end catch
45 } // end main
46 } // end class Demo2
47
48 // subclass of Exception
49 class ExceptionA extends Exception
50 {
51 // empty class body
52 } // end class ExceptionA

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

1 // Exercise 13.19 Solution: CompileError.java


2 // Program generates a compiler error.
3 import java.io.IOException;
4
5 public class CompileError
6 {
7 public static void main( String args[] )
8 {
9 try
10 {
11 throw new IOException();
12 } // end try
13 catch ( Exception exception ) // superclass exception
14 {
15 exception.printStackTrace();
16 } // end catch
17 catch ( IOException ioException ) // subclass exception
18 {
19 System.err.println( "IOException" );
20 } // end catch
21 } // end main
22 } // end class CompileError

CompileError.java:17: exception java.io.IOException has already been caught


catch ( IOException ioException ) // subclass exception
^
1 error

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

1 // Exercise 13.20 Solution: Demo3.java


2 // Program demonstrates a constructor that throws an exception.
3
4 class SomeClass
5 {
6 // constructor throws exception
7 public SomeClass() throws Exception
8 {
9 throw new Exception();
10 } // end SomeClass constructor
11 } // end class SomeClass
12
13 public class Demo3
14 {
15 public static void main( String args[] )
16 {
17 SomeClass testObject;
18
19 try // instantiate SomeException object
20 {
21 testObject = new SomeClass();
22 } // end try
23 catch ( Exception exception )
24 {
25 System.out.println( exception.toString() );
26 } // end catch
27 } // end main
28 } // end class Demo3

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:

1 // Exercise 13.21 Solution: Demo4.java


2 // Program demonstrates rethrowing an exception.
3
4 public class Demo4
5 {

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

6 public static void main( String args[] )


7 {
8 try // call someMethod
9 {
10 someMethod();
11 } // end try
12 catch ( Exception exception )
13 {
14 System.err.printf( "%s\n\n", exception.getMessage() );
15 exception.printStackTrace();
16 } // end try
17 } // end main
18
19 // call someMethod2; rethrow Exceptions back to main
20 public static void someMethod() throws Exception
21 {
22 try // call someMethod2
23 {
24 someMethod2();
25 } // end try
26 catch ( Exception exception2 )
27 {
28 throw exception2; // rethrow the Exception
29 } // end catch
30 } // end method someMethod
31
32 // throw Exception back to someMethod
33 public static void someMethod2() throws Exception
34 {
35 throw new Exception( "Exception thrown in someMethod2" );
36 } // end method someMethod2
37 } // end class Demo4

Exception thrown in someMethod2

java.lang.Exception: Exception thrown in someMethod2


at Demo4.someMethod2(Demo4.java:35)
at Demo4.someMethod(Demo4.java:24)
at Demo4.main(Demo4.java:10)

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:

1 // Exercise 13.22 Solution: Demo5.java


2 // Program demonstrates rethrowing an exception.
3
4 public class Demo5
5 {

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

6 public static void main( String args[] )


7 {
8 try // call method someMethod
9 {
10 someMethod();
11 } // end try
12 catch ( ExceptionB exception )
13 {
14 System.err.printf( "Handled in main: %s", exception );
15 } // end catch
16 catch ( Exception exception )
17 {
18 exception.printStackTrace();
19 } // end catch
20 } // end main
21
22 // call method someMethod2
23 public static void someMethod() throws Exception
24 {
25 try
26 {
27 someMethod2();
28 } // end try
29 catch ( ExceptionA exception ) // only catches ExceptionA
30 {
31 System.err.printf(
32 "Handled execeptionA in someMethod: ", exception );
33 } // end catch
34 } // end method someMethod
35
36 // throw Exception
37 public static void someMethod2() throws Exception
38 {
39 throw new ExceptionB();
40 } // end method someMethod2
41 } // end class Demo5
42
43 // subclasses of Exception
44 class ExceptionA extends Exception
45 {
46 // empty class body
47 } // end class ExceptionA
48
49 class ExceptionB extends Exception
50 {
51 // empty class body
52 } // end class ExceptionB

Handled in main: ExceptionB

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

You might also like