Java Reference
In-Depth Information
Suppose the main method invokes method1 , method1 invokes method2 , method2
invokes method3 , and method3 throws an exception, as shown in Figure 14.3. Consider the
following scenario:
If the exception type is Exception3 , it is caught by the catch block for han-
dling exception ex3 in method2 . statement5 is skipped, and statement6 is
executed.
If the exception type is Exception2 , method2 is aborted, the control is returned to
method1 , and the exception is caught by the catch block for handling exception
ex2 in method1 . statement3 is skipped, and statement4 is executed.
If the exception type is Exception1 , method1 is aborted, the control is returned to
the main method, and the exception is caught by the catch block for handling
exception ex1 in the main method. statement1 is skipped, and statement2 is
executed.
If the exception type is not caught in method2 , method1 , or main , the program ter-
minates, and statement1 and statement2 are not executed.
An exception
is thrown in
method3
main method {
...
try {
...
invoke method1;
statement1;
}
catch (Exception1 ex1) {
Process ex1;
}
statement2;
}
method1 {
...
try {
...
invoke method2;
statement3;
}
catch (Exception2 ex2) {
Process ex2;
}
statement4;
}
method2 {
...
try {
...
invoke method3;
statement5;
}
catch (Exception3 ex3) {
Process ex3;
}
statement6;
}
Call stack
method3
method2
method2
method1
method1
method1
main method
main method
main method
main method
F IGURE 14.3 If an exception is not caught in the current method, it is passed to its caller. The process is repeated until
the exception is caught or passed to the main method.
Note
Various exception classes can be derived from a common superclass. If a catch block
catches exception objects of a superclass, it can catch all the exception objects of the
subclasses of that superclass.
catch block
Note
The order in which exceptions are specified in catch blocks is important. A compile
error will result if a catch block for a superclass type appears before a catch block for a
subclass type. For example, the ordering in (a) on the next page is erroneous, because
RuntimeException is a subclass of Exception . The correct ordering should be as
shown in (b).
order of exception handlers
Search WWH ::




Custom Search