March 24, 2024

Multiple Catch Blocks in Java

If hearing the term try-catch block is giving you an idea that you can have a try block and a single associated catch block then that is a wrong idea. You can have multiple catch blocks associated with a try block. In this post we’ll see examples of multiple catch blocks in Java exception handling.

Refer Multi-Catch Exception in Java to seen another way of grouping multiple catch blocks using multi-catch statement available from Java 7.

You enclose the code that may throw an exception in try block but the enclosed code may throw more than one exception too. In order to handle these exceptions you can provide multiple catch blocks in Java. If an exception is thrown the exception handling mechanism looks for the catch block with an argument that matches the type of the exception thrown. Only the matching catch clause out of the multiple catch blocks is executed. After the matching catch block is executed, execution continues after the try-catch block.

Example of multiple catch blocks in Java

In this example program there is an array of length 3 in the method calculateValue(). Index of the array is passed as an argument to the method. Since the array has value 0 at index 1 so passing 1 as an index will result in ArithmeticException because of the division by zero.

Same way passing 4 as an index will result in ArrayIndexOutOfBoundsException as the length of array is 3. To handle these multiple exception scenarios there are multiple catch blocks associated with the try block.

public class MultipleCatch {
  private void calculateValue(int i){
    int arr[] = {6, 0, 3};
    try{
      int num = 7/arr[i];
    }catch(ArithmeticException exp){
      exp.printStackTrace();
    }catch(ArrayIndexOutOfBoundsException exp){
      exp.printStackTrace();
    }catch(Exception exp){
      exp.printStackTrace();
    }
    System.out.println("After the try-catch block");
  }

  public static void main(String[] args) {
    MultipleCatch obj = new MultipleCatch();
    obj.calculateValue(1);
    obj.calculateValue(4);
  }
}
Output
java.lang.ArithmeticException: / by zero
	at com.knpcode.MultipleCatch.calculateValue(MultipleCatch.java:7)
	at com.knpcode.MultipleCatch.main(MultipleCatch.java:21)
After the try-catch block
java.lang.ArrayIndexOutOfBoundsException: 4
	at com.knpcode.MultipleCatch.calculateValue(MultipleCatch.java:7)
	at com.knpcode.MultipleCatch.main(MultipleCatch.java:22)
After the try-catch block

Maintaining exception hierarchy in multiple catch blocks

While using multiple catch blocks in Java you will have to keep exception hierarchy in mind, which means you will have to ensure that any exception super class doesn’t come before its exception sub-classes.

This should be ensured because a catch statement having an exception super class as an argument will be able to catch exception of its type and any of its subclass too. Thus, placing a catch statement having sub-class as an argument after the catch statement with super class as argument would mean the catch statement with sub-class is unreachable. Moreover unreachable code causes compile time error in Java so you will get compilation error for any such misplaced catch statement.

In the previous example the last catch statement has Exception class object as an argument to catch any other type of exception. Since Exception class is super class of both the ArithmeticException and ArrayIndexOutOfBoundsException so placing that catch statement first will result in compile time error. Just tweak the above example and place the catch statement with Exception class object as argument before the other catch blocks.

public class MultipleCatch {
  private void calculateValue(int i){
    int arr[] = {6, 0, 3};
    try{
      int num = 7/arr[i];
    }
    catch(Exception exp){
      exp.printStackTrace();
    }catch(ArithmeticException exp){
      exp.printStackTrace();
    }catch(ArrayIndexOutOfBoundsException exp){
      exp.printStackTrace();
    }
    System.out.println("After the try-catch block");
  }

  public static void main(String[] args) {
    MultipleCatch obj = new MultipleCatch();
    obj.calculateValue(1);
    obj.calculateValue(4);
  }
}

That will result in compile time error with compiler complaining about the unreachable code.

Unresolved compilation problems: 
	Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception
	Unreachable catch block for ArrayIndexOutOfBoundsException. It is already handled by the catch block for Exception

	at com.knpcode.MultipleCatch.calculateValue(MultipleCatch.java:11)
	at com.knpcode.MultipleCatch.main(MultipleCatch.java:21)

Important points

  1. There may be multiple catch blocks after a try block.
  2. If an exception is thrown in try block the catch block with matching exception type is executed.
  3. Only one of the multiple catch blocks is executed.
  4. Multiple catch blocks must be placed in the order specific to general.

That's all for the topic Multiple Catch Blocks in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment