You can nest exception handlers within one another. A try catch or a last block can contain another set of try catch final sequence. In this scenario, when a particular catch block cannot handle an Exception, this exception is re-thrown. The outer set of try catch handler will handle this exception. 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 final sequence has been nested within another try-catch final sequence. The inner try block throws an ArithmeticException which it could not handle. Hence, this exception is re-thrown by the inner block which is handled in the outer final block.

Note that all the final blocks that come in the program’s way are exciting. Such nesting as try-catch blocks can also occur in the 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 has been re-thrown. This try catch sequence of meth() is nested within the try-catch sequence of the main() by the method call. Therefore, the exception is processed by the last 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