Nested try Statements


The try statement can be nested. That is, one try statement may be inside another try block. Each time a try statement is entered, the context of this exception is pressed on the stack. If an internal try statement does not have a catch handler for a particular exception, the stack is unwanted and the catch handlers in the next try statement are inspected for a match. It is caught until a capture statement is successful, or until all statements in the nested trial have been completed. If a catch does not match the statement, the Java run-time system will handle the exception. Here is an example that uses nested try statements :

Program
public class Main 
{
  public static void main(String[] args) 
  {
   try{
    int a = 0;
    int b = 12;
    System.out.println("a = " + a);
    int d = b/a;
    try{
     int c[]={1,2,3};
     System.out.println("c[4] = " + c[4]);
    }
    catch(ArrayIndexOutOfBoundsException e){
     System.out.println("Array index out-of-bounds" + e);
    }
   }
   catch(ArithmeticException ae){
    System.out.println("Divide by 0 : " + ae);
   }
  }
}

In the example above, when "a = 0" the first try block has an exception so the inner try block does not work. But later when "a = 1" is done, after successfully executing the first try block, the second try block is executed and there is an exception.