Java Reference
In-Depth Information
Figure 7-3 illustrates the normal sequence of execution in an arbitrary try - catch - finally set of blocks.
If there's a return statement in the try block, this is executed immediately after the finally block completes
execution — so this prevents the execution of any code following the finally block. A return statement in
a finally block causes an immediate return to the calling point, and the code following the finally block
isn't executed in this case.
Execution When an Exception Is Thrown
The next block of output corresponds to an ArithmeticException being thrown and caught in the di-
vide() method:
First try block in divide() entered
Arithmetic exception caught in divide()
index = 0 Expression: array[0]/array[1] is 10/0
finally block in divide()
Executing code after try block in divide()
result = 2
The exception is thrown because the value of the second element in the array x is zero. When the excep-
tion occurs, execution of the code in the try block is stopped, and you can see that the code that follows the
catch block for the exception in the divide() method is then executed. The finally block executes next,
followed by the code after the finally block. The value in the last element of the array isn't changed from
its previous value, because the exception occurs during the computation of the new value, before the result
is stored.
The general sequence of execution in a try - catch - finally set of blocks when an exception occurs is
shown in Figure 7-4 .
FIGURE 7-4
 
 
Search WWH ::




Custom Search