A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Nested try block

Nested Try

Nested try block

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

Why we need nested try block

It is required when different blocks like outer and inner may cause different exceptions.

Syntax-





//Main try block
try 
{
   statement of main try;
   //try-catch block inside try block
   try 
   {
      statement;
      //try-catch block inside nested try block
    
      try 
      {
         statement ;
      }
    
      catch(Exception ex)
      {
         //Exception code
      }
   }
  
   catch(Exception ex)
   {
      //Exception code
   }
   
}

//Catch for Main try block
catch(Exception ex) 
{
  //Exception code
}
//rest of the code...


 

Nested try block example:-





class Test1
{  
   public static void main(String args[])
   {  
     try
     {  
       try
       {  
          System.out.println("Cannot divide by zero..divider should be greater than 0..");  
          int y =25/0;  
       }
   
       catch(ArithmeticException e)
       {
          System.out.println(e);
       }  
   
       try
       {  
        
          int a[]=new int[5];  
          for(int i=0;i <=5;i++)
          {
             System.out.println(a[5]); 
       }
     }
   
     catch(ArrayIndexOutOfBoundsException e)
     {
       System.out.println(e);
     } 
   
     try
     {  
       String s=null;
       System.out.println(s.length());
     }
   
     catch(NullPointerException e)
     {
       System.out.println(e);
     }
     
     System.out.println("i am not a part of try block...");
     
    }
  
    catch(Exception e)
    {
      System.out.println("Exception Handeled with catch..");
    }  
  
    System.out.println("Rest of the data normal flow...");  
  }  
} 

OutPut:-
Cannot divide by zero..divider should be greater than 0..
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
java.lang.NullPointerException
i am not a part of try block...
Rest of the data normal flow...


 











LEARN TUTORIALS

.

.