Java Reference
In-Depth Information
The output of Listing 9-2 is nicer than that of Listing 9-1. It tells you exactly what happened when the program
was executed. Notice that the program did not terminate when the exception occurred because you handled the
exception. The program executed the last statement that printed the “At the end of the program” message.
Transfer of Control
You need to understand very precisely the flow of control when an exception is thrown in a
try
block. First, the Java
runtime creates an object of the appropriate class to represent the exception that has occurred. The first
catch
block
following the
try
block is checked. If the exception object can be assigned to the parameter for the
catch
block, the
parameter of the
catch
block is assigned the reference of the exception object, and the control is transferred to the
body of the
catch
block. When the
catch
block finishes executing its body, the control is transferred to the point
following the
try-catch
block. It is very important to note that after executing the
catch
block the control is not
transferred back to the
try
block. Rather, it is transferred to the code that follows the
try-catch
block. If a
try
block
has many
catch
blocks associated with it, a maximum of one
catch
block is executed. Figure
9-1
shows the transfer of
control in a typical Java program when an exception occurs in a
try
block.
Some statements go here...
try {
try-statement-1;
try-statement-2;
try-statement-3;
}
catch(Exception1 e1) {
catch-statement-11;
catch-statement-12;
}
catch(Exception2 e2) {
catch-statement-21;
catch-statement-22;
}
catch(Exception3 e3) {
catch-statement-31;
catch-statement-32;
}
statement-1;
more statements go here...
Figure 9-1.
Transfer of control when an exception occurs in a try block
You assume that when
try-statement-2
is executed, it throws an exception of type
Exception2
. When the
exception is thrown, the control is transferred to the second
catch
block, and
catch-statement-21
and
catch-statement-22
are executed. After
catch-statement-22
is executed, control is transferred outside the
try-
catch
block, and
statement-1
starts executing. It is very important to understand that
try-statement-3
is never
executed when
try-statement-2
throws an exception. Among three
catch
blocks, a maximum of one will be
executed when a statement inside the
try
block throws an exception.
Exception Class Hierarchy
The Java class library contains many exception classes. Figure
9-2
shows a few exception classes. Note that the
Object
class does not belong to the family of exception classes. It is shown in the figure as an ancestor of the
Throwable
class
in the inheritance hierarchy.