Nested try block in java

When we put try-block within another try-block then it is known as Nested try-block.


Why use nested try block?

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested, one within another. In java, this can be done using nested try blocks. A try statement can be inside the block of another try.

Syntax of Nested try block

Syntax:


try
{	
	statement 1;
        statement 2;

	try
	{

	statement 1;
        statement 2;

	}catch(ExceptionType e)
	{
	//handling code
	}

}catch(ExceptionType e)
{
	//handling code
}

Example of nested try


//example of Nested try-block
class Example {
    public static void main(String arr[]) {
        System.out.println("Start..");
        //outer try block
        try {
            //first inner try
            try {
                int a = 3 / 0;

            } catch (ArithmeticException e) {
                e.printStackTrace();
            }
            //second inner try

            try {
                String str = null;
                int l = str.length();
            } catch (NullPointerException e) {
                System.out.println("may be you are trying to use null reference");
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        System.out.println("End..");
    }
}
Start..
java.lang.ArithmeticException: / by zero
	at Example.main(Test.java:10)
may be you are trying to use null reference
java.lang.NullPointerException
	at Example.main(Test.java:20)
End..