Exception handlers can be nested within one another. A try catch or a final block can contain another set of try catch finally sequence. In this scenario, when a particular catch block cannot handle an Exception, this exception is rethrown. This exception will 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 exciting. Such nesting to 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 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 the method call. Therefore, the exception is processed by the final 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