Java Reference
In-Depth Information
The sequence of execution when no exceptions occur is shown in the diagram.
try{
Execution starts
at the beginning
of the
//Code that can throw exceptions
try
block.
}
catch( e){
MyException1
After a normal
exit from a
block, the
block is
executed, before
any return in
the
//Code to process exception
}
try
finally
catch( e){
MyException2
block.
try
//Code to process exception
}
finally{
//Code to execute after the try block
If there is no statement
in the or blocks,
execution continues with code
following the
return
try finally
}
finally
block.
Normal Execution Sequence
The previous diagram 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 will be 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 will cause an immediate return to the calling
point and the code following the finally block wouldn't be executed in this case.
Execution when an Exception is Thrown
The next block of five lines in the output correspond to an ArithmeticException being thrown and
caught in the method divide() . The exception is thrown because the value of the second element in
the array x is zero. When the exception 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 an arbitrary try-catch-finally set of blocks when an
exception occurs is shown here.
Search WWH ::




Custom Search