Java Reference
In-Depth Information
This causes an ArrayIndexOutOfBoundsException to be thrown in the try block, which is then caught.
However, the code at the end of the method, which is executed after the finally block, throws another ex-
ception of this type. This can't be caught in the divide() method because the statement throwing it isn't in
a try block. Because this exception isn't caught in the divide() method, the method terminates immedi-
ately at the point where the divide() method was called. This causes the code in the relevant catch block
in main() to be executed as a consequence of the uncaught exception.
An exception that isn't caught in a method is always propagated upward to the calling method. It con-
tinues to propagate up through each level of calling method until either it is caught or the main() method
is reached. If it isn't caught in main() , the program terminates and a suitable message is displayed. This
situation is illustrated in Figure 7-5 .
FIGURE 7-5
The sequence of events in Figure 7-5 is shown by the numbers on the arrows. It shows method1() calling
method2() , which calls method3() , which calls method4() , in which an exception of type Exception2 is
thrown. This exception isn't caught in method4() , so execution of method4() ceases, and the exception is
thrown to method3() . It isn't caught and continues to be thrown until it reaches method1() where there's a
catch block to handle it.
In our TryBlockTest example, execution continues in main() with the output statements outside the first
try block. The read() method pauses the program until you press the Enter key. No exception is thrown,
and execution ends after the code in the finally block is executed. The finally block is tied to the try
block that immediately precedes it and is executed even though there's a return statement in the try block.
Nested try Blocks
I don't go into these in detail, but you should note that you can have nested try blocks, as Figure 7-6 illus-
trates.
FIGURE 7-6
 
 
 
 
Search WWH ::




Custom Search