Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Nested try statements

In Java, try statement/block can be nested inside another try block.

try
{
     try
     {
				
     }
     catch(ExceptionType reference)
     {
				
     }
}
catch(ExceptionType reference)
{
			
}

If nested try block generates an exception that cannot be handled by its catch clauses, then that exception must be handled by catch clause of the outer try block. Otherwise, JVM will provide default exception handler leading to abnormal termination of the program.

Example – I

import java.util.Scanner;

class NestedTry  
{
    public static void main(String args[])
    {
        try
        {
            try
            {
                System.out.println("Enter any number :: ");
                Scanner in = new Scanner(System.in);
                int num = in.nextInt();
                in.close();
                int i = 10/num;
                System.out.println("i = "+i);
                String str = null;
                System.out.println(str.length());
           }
           catch(ArithmeticException e)
           {
               System.out.println("Arithmetic Exception Handled");
           }
        }
        catch(NullPointerException e)
        {
            System.out.println("Null Pointer Exception Handled");
        }
    }
}

If entered num is zero

Output

Enter any number ::
0
Arithmetic Exception Handled

If entered number is other than zero

Output

Enter any number ::
2
i = 5
Null Pointer Exception Handled

 

Leave a reply