Thursday, 8 January 2015

Multiple catch block in Exception Handling in java

Multiple catch block in Exception Handling:

If you have to perform different tasks at the occrence of different Exceptions,you have to use multple catch blocks.

For Example:  

class Test{
public static void main(String []args){
try{
int x[]=new int[5];
x[5]=20/0;
}
catch(ArithmeticException ex) {  System.out.println("task1 is completed");  }
catch(ArrayIndexOutOfBoundsException ex) {  System.out.println("task 2 completed");   }
catch(Exception ex) {  System.out.println("common task completed");  }
System.out.println("rest of the code.....");
 }
}

Output: task1 completed
rest of the code.....

Note: At a time only one Exception is occured and at a time only one catch block is executed.

Note: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception.

Explanation: Suppose you want to catch ArithmeticException, then first use ArithmeticException in catch block then Exception.
i.e. catch( ArithmeticException ex) { }
     catch( Exception ex) { }

Note: If you don't fallow these rules then Compile-time error would occure.

For Example:

class Test{
public static void main(String []args){
try{
int x[]=new int[10];
x[12]=20/0;
}
catch(Exception e)  {System.out.println("common task completed");  }
catch(ArithmeticException e)  {System.out.println("task1 is completed");  }
catch(ArrayIndexOutOfBoundsException e)  {System.out.println("task 2 completed");  }
System.out.println("rest of the code...");
 }
}

Output: Compile-time error

Next>> What is Nested try block in Java

No comments:

Post a Comment