Java Reference
In-Depth Information
try{
Execution starts
at the beginning
of the
//Code that does throw exceptions
block.
try
}
catch( e){
MyException1
Execution breaks off at
the point where the exception
occurs, and control transfers
to the start of the
block for the exception.
//Code to process exception
catch
}
catch( e){
MyException2
//Code to process exception
}
After the catch block
has executed, the finally
block is executed.
finally{
//Code to execute after the try block
If there is no statement
in the or blocks,
execution continues with code
following the
return
catch finally
}
block.
finally
Exception Execution Sequence
Execution of the try block stops at the point where the exception occurs, and the code in the catch
block for the exception is executed immediately. If there is a return statement in the catch block,
this isn't executed until after the finally block has been executed. As discussed earlier, if a return
statement that returns a value is executed within a finally block, that value will be returned, not the
value from any previous return statement.
Execution when an Exception is not Caught
The next block of six lines in the output is a consequence of the third call to the method divide() . 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
exception of this type. This can't be caught in the method divide() because the statement causing it isn't in
a try block. Since this exception isn't caught in the method divide() , the method terminates immediately
and the same exception is thrown in main() at the point where the divide() method was called. This
causes the code in the relevant catch block in main() to be executed in consequence.
An exception that isn't caught in a method is always propagated upwards to the calling method. It will
continue 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 will terminate and a suitable message will
be displayed. This situation is illustrated here.
Search WWH ::




Custom Search