All for Joomla All for Webmasters

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.     try{
  9.     int a[]=new int[5];
  10.     a[5]=4;
  11.     }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
  12.     System.out.println(“other statement);
  13.   }catch(Exception e){System.out.println(“handeled”);}
  14.   System.out.println(“normal flow..”);
  15.  }
  16. }
PinIt
submit to reddit

Leave a Reply

Top