Java Reference
In-Depth Information
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 ex-
ecuted until after the
finally
block has been executed. As I discussed earlier, if a
return
statement that
returns a value is executed within a
finally
block, that value is returned, not the value from any previous
return
statement.
If an exception is thrown in a
finally
block, this will terminate the execution of the code in the
finally
block and the method. You can see the effect if you add the following statement to the
finally
block in
divide()
:
int result = array[index]/array[index+1];
When
ArithmeticException
is thrown in the
try
block, the same exception is thrown in the
finally
block as a result of this statement. You will see from the output that the
divide()
method terminates and
the exception is caught in
main()
. Try moving the statement to the catch block for
ArithmeticException
.
You'll see that the
finally
block still executes even though an exception is thrown in the
catch
block.
Execution When an Exception Is Not Caught
The next block of output is a consequence of the third call to the
divide()
method:
First try block in divide() entered
Index-out-of-bounds exception caught in divide()
array length = 3 index = 1
finally block in divide()
Executing code after try block in divide()
Index-out-of-bounds exception caught in main()
Outside first try block in main()