Java Reference
In-Depth Information
11.7 Stack Unwinding and Obtaining Information from
an Exception Object
When an exception is thrown but not caught in a particular scope, the method-call stack is
“unwound,” and an attempt is made to catch the exception in the next outer try block.
This process is called stack unwinding . Unwinding the method-call stack means that the
method in which the exception was not caught terminates , all local variables in that meth-
od go out of scope and control returns to the statement that originally invoked that method.
If a try block encloses that statement, an attempt is made to catch the exception. If a try
block does not enclose that statement or if the exception is not caught, stack unwinding
occurs again. Figure 11.6 demonstrates stack unwinding, and the exception handler in
main shows how to access the data in an exception object.
Stack Unwinding
In main , the try block (lines 8-11) calls method1 (declared at lines 35-38), which in turn
calls method2 (declared at lines 41-44), which in turn calls method3 (declared at lines 47-
50). Line 49 of method3 throws an Exception object—this is the throw point . Because the
throw statement at line 49 is not enclosed in a try block, stack unwinding occurs—
method3 terminates at line 49, then returns control to the statement in method2 that in-
voked method3 (i.e., line 43). Because no try block encloses line 43, stack unwinding oc-
curs again— method2 terminates at line 43 and returns control to the statement in method1
that invoked method2 (i.e., line 37). Because no try block encloses line 37, stack unwinding
occurs one more time— method1 terminates at line 37 and returns control to the statement
in main that invoked method1 (i.e., line 10). The try block at lines 8-11 encloses this state-
ment. The exception has not been handled, so the try block terminates and the first
matching catch block (lines 12-31) catches and processes the exception. If there were no
matching catch blocks, and the exception is not declared in each method that throws it, a
compilation error would occur. Remember that this is not always the case—for unchecked
exceptions, the application will compile, but it will run with unexpected results.
1
// Fig. 11.6: UsingExceptions.java
2
// Stack unwinding and obtaining data from an exception object.
3
4
public class UsingExceptions
5
{
6
public static void main(String[] args)
7
{
8
try
9
{
10
method1();
11
}
12
catch (Exception exception) // catch exception thrown in method1
13
{
14
System.err.printf( "%s%n%n" ,
exception.getMessage()
);
15
exception.printStackTrace();
16
Fig. 11.6 | Stack unwinding and obtaining data from an exception object. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search