Nested Try Example Java Program


Definition

The statements within the try block are executed, and if any of them throws an exception, execution of the block is discontinued and the exception is handled by the catch block.

Syntax

...
try  {  
    //Do something
    try {  
        //Do something
    }  
    catch(Exception e){  
    }  
}  
catch(Exception e){  
}  
...

Nested Try Example Program

public class NestedTryDemo {
    public static void main(String[] args) {
        try {
            checkException();
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException");
        } finally {
            System.out.println("Finally outside method");
        }
    }
    public static void checkException() {
        try {
            int res = 3 / 0;
        } finally {
            System.out.println("Finally inside method");
        }
    }
}

Sample Output

Output is:
Finally inside method
ArithmeticException
Finally outside method