Multi-catch feature for exception handling in Java

This post explains handling multiple exceptions using multi-catch feature.

 

Handling multiple catch before Java 7

 

Before Java 7, we had to write multiple catch blocks to catch more than one exceptions.

 

Here is a piece of code that catches a divide by zero and array index exception.

 

public class ExceptionExample {

  public static void main(String[] args) {
    int num = 10;
    int div = 0;
    int arr[] = {1};
    try{
      
      int q = num/div;
      arr[10] = 11;
    }
    catch(ArithmeticException e){
      System.out.println("Exception : " + e);
    }
    catch(ArrayIndexOutOfBoundsException e){
      System.out.println("Exception : " + e);
    }
  }

}


 

Here the try block will generate an ArithmeticException because of division by zero and since we are accessing array element at an invalid index, ArrayIndexOutOfBoundsException will be created.

 

The two catch statements handle these two exceptions.

 

Multi-catch feature

 

Starting with Java 7, multi-catch feature allows two or more exceptions to be caught by the same catch clause.

 

If the exception handlers use the same code, using single catch clause to handle all exceptions with avoid code duplication.

 

To use the multi-catch, we need to separate each exception type in the catch clause with the OR symbol “|”.

 

Each multi-catch parameter is implicitly final.

 

So, using multi-catch we can rewrite the catch statements in previous program as :

 

catch(ArithmeticException | ArrayIndexOutOfBoundsException e)

 

Here is the complete example :

 

public class MultiCatchExample {

  public static void main(String[] args) {
    int num = 10;
    int div = 0;
    int arr[] = {1};
    try{
      
      int q = num/div;
      arr[10] = 11;
    }
    catch(ArithmeticException | ArrayIndexOutOfBoundsException e){
      System.out.println("Exception : " + e);
    }
    
  }

}

 

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags