java Multiple catch block

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block.

Let's see a simple example of java multi-catch block.

  1. public class TestMultipleCatchBlock{  
  2.   public static void main(String args[]){  
  3.    try{  
  4.     int a[]=new int[5];  
  5.     a[5]=30/0;  
  6.    }  
  7.    catch(ArithmeticException e){System.out.println("task1 is completed");}  
  8.    catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}  
  9.    catch(Exception e){System.out.println("common task completed");}  
  10.   
  11.    System.out.println("rest of the code...");  
  12.  }  
  13. }  

Test it Now

Output:task1 completed
       rest of the code...

Rule: At a time only one Exception is occurred and at a time only one catch block is executed.

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

  1. class TestMultipleCatchBlock1{  
  2.   public static void main(String args[]){  
  3.    try{  
  4.     int a[]=new int[5];  
  5.     a[5]=30/0;  
  6.    }  
  7.    catch(Exception e){System.out.println("common task completed");}  
  8.    catch(ArithmeticException e){System.out.println("task1 is completed");}  
  9.    catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}  
  10.    System.out.println("rest of the code...");  
  11.  }  
  12. }  

Test it Now

Output:

Compile-time error