by Dinesh Thakur

So far we have been using just single try statement. However, it is possible to nest a try statement inside another try statement. If one try block does not have a corresponding catch block that handles the exception, Java will search the next outer try block for a catch block that will handle the exception, back through successive nesting. If the Java cannot find the catch block for the exception, it will pass the exception to its default exception handler.

Often nested try statements are used to allow different categories of errors to be handled in different ways. Many programmers use an inner try block to catch the less severe errors and outer try block to catch the more severe errors.

Now let us consider the following program

public class NestedTry

{
     public static void main(String[] args)
     {
       int[] num={12,24,36,48,60,72};
       int[] den={2,4,0,6};
       for(int i=0;i<num.length;i++)
           {
                try
               {
                    try
                    {
                         System.out.println(num[i]+"/"+den[i]+" = "+num[i]/den[i]);
                    }
                    catch(ArithmeticException e)
                    {
                        System.out.println("Inner:integer division y 0 not possile");
                    }
               }
               catch(ArrayIndexOutOfBoundsException e)
               {
                       System.out.println("outer:Array Index out of Bounds");
               }
           }
      }
}

Nested Try Statements in Java Examples