Java Reference
In-Depth Information
int (...) {
try
method1
{
int (...) {
method3(...);
method2
method2
(...);
uncaught
}
catch( e ) {
//Code to process exception
Exception2
}
propagated
Exception1
Exception2
caught
uncaught
Exception2
int (...) {
method4(...);
method3
propagated
{
catch( e ) {
//Code to process exception
} finally {
//Code to execute after the try block
Exception2
}
finally block
executed
uncaught
propagated
Exception2
int (...) {
//Exception 2
thrown
method4
}
}
}
This 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 in method3() . It isn't caught, and continues to be
rethrown until it reaches method1() where there's a catch block to handle it.
In our Try It Out , 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
We will not be going into these in detail, but you should note that you can have nested try blocks, as
illustrated in this diagram.
try {
try
{
//1st inner try block code...
} catch( ) {
Exception1
//...
}
Exceptions of type thrown
anywhere in here that are not caught,
will be caught by the
Exception2
//Outer try block code...
block for the
catch
outer
block.
try
try {
//2nd inner try block code...
}
catch( e ) {
Exception1
//try block code...
}
}
catch( e ){
//Outer catch block code...
Exception2
}
Search WWH ::




Custom Search