Java Nested Try Block


The try block within a try block is known as nested try block in java.

Syntax

 try  
 {  
    statement 1;  
    statement 2;  
    try  
    {  
        statement 1;  
        statement 2;  
    }  
    catch(Exception e)  
    {  
    }  
 }  
  catch(Exception e)  
  {  
  }

Example

public class nested_try {

    public static void main(String[] args) {
       
        try
        {
            int a=2;
            int b=4;
            int c=2;
            int x=7;
            int z;
            
            int p[]={2};
            p[3]=33;
            try
            {
                z=x/((b*b)-(4*a*c));
                System.out.println("The Value of Z="+z);
            }
             catch(ArithmeticException e)
              {
               System.out.println("Divide by Zero");
               System.out.println(e);
              }
         }
          catch(ArrayIndexOutOfBoundsException e)
          {
           System.out.println("Array Index Error"); 
           System.out.println(e);
          }
      }
 }
Output
Array Index Error
java.lang.ArrayIndexOutOfBoundsException: 3

Share this article on