AdSense

AdSense3

Monday, 8 September 2014

Java Nested try block

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

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:

  1. ....  
  2. try  
  3. {  
  4.     statement 1;  
  5.     statement 2;  
  6.     try  
  7.     {  
  8.         statement 1;  
  9.         statement 2;  
  10.     }  
  11.     catch(Exception e)  
  12.     {  
  13.     }  
  14. }  
  15. catch(Exception e)  
  16. {  
  17. }  
  18. ....  

Java nested try example

Let's see a simple example of java nested try block.
  1. class Excep6{  
  2.  public static void main(String args[]){  
  3.   try{  
  4.     try{  
  5.      System.out.println("going to divide");  
  6.      int b =39/0;  
  7.     }catch(ArithmeticException e){System.out.println(e);}  
  8.    
  9.     try{  
  10.     int a[]=new int[5];  
  11.     a[5]=4;  
  12.     }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}  
  13.      
  14.     System.out.println("other statement);  
  15.   }catch(Exception e){System.out.println("handeled");}  
  16.   
  17.   System.out.println("normal flow..");  
  18.  }  
  19. }  

1 comment: