Nested try catch blocks


Exception handlers can be nested within one another. A try, catch or a finally block can in turn contains another set of try catch finally sequence. In such a scenario, when a particular catch block is unable to handle an Exception, this exception is rethrown. This exception would be handled by the outer set of try catch handler. Look at the following code for Example.
import java.util.InputMismatchException;
public class Nested {
public static void main(String[] args) {
try {
System.out.println(“Outer try block starts”);
try {
System.out.println(“Inner try block starts”);
int res = 5 / 0;
} catch (InputMismatchException e) {
System.out.println(“InputMismatchException caught”);
} finally {
System.out.println(“Inner final”);
}
} catch (ArithmeticException e) {
System.out.println(“ArithmeticException caught”);
} finally {
System.out.println(“Outer finally”);
}
}
}
The output is
Outer try block starts
Inner try block starts
Inner final
ArithmeticException caught
Outer finally Outer finally
In this example, one try catch finally sequence has been nested within another try catch finally sequence. The inner try block throws an ArithmeticException which it could not handle. Hence, this exception is rethrown by the inner block which is handled in the outer finally block. Note that all the finally blocks that come in the way of the program are excited. Such nesting of try catch blocks can also occur in case of method calls. Nesting may not be very explicit in such cases. Look at the following example which contains two methods main() and meth(). Both the methods have exception handlers. meth() is invoked from the method main(). The try block in meth() throws an ArithmeticException which it could not handle. Hence, it is rethrown. This try catch sequence of meth() in nested within the try catch sequence of main() by way of method call. Therefore, the exception is processed by the finally block of the main() method.
public class Nested {

Public static void main(String[] args) {
try {
meth();
} catch (ArithmeticException e) {
System.out.println(“ArithmeticException caught”);
} finally {
System.out.println(“Outer finally”);
}
}

Public static void meth() {
try {
int res = 3 / 0;
} finally {
System.out.println(“Finally in meth”);
}
}
}

The output is
Finally in meth
ArithmeticException caught
Outer finally
Author: , 0000-00-00