Friday, 22 May 2015

Multiple catch blocks in Java exception handling

There might be a case when a code enclosed with in a try block throws more than one exception. To handle these types of situations, multiple catch blocks can be specified where each catch clause catches a different type of exception. When an exception is thrown, every catch statement is inspected in order, and the first one whose type matches that of the thrown exception is executed.

After one of the catch statement, out of the multiple catch blocks, executes the others are bypassed and execution continues after the try-catch block.

Notice that with Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code.

Example

In this program there is an array with only one element which is zero. From main method when calculateValue method is called a parameter is passed which is used as an index of the array.

First time 0 is sent which will mean divide by a[0]. Since the value at that index is 0 thus it will result in divide by 0 and ArithmeticException will be thrown.

Next time 2 is sent but array has only one element so trying to access a[2] will result in ArrayIndexOutOfBoundsException.

In the code there are multiple catch blocks and both of these exceptions will be caught by separate catch blocks.

public class MultipleCatchDemo {
    private void calculateValue(int i){
        int a[] = {0};
        try{
            int b = 7/a[i];
        }catch(ArithmeticException aExp){
            aExp.printStackTrace();
        }catch(ArrayIndexOutOfBoundsException aiExp){
            aiExp.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MultipleCatchDemo mcDemo = new MultipleCatchDemo();
        mcDemo.calculateValue(0);
        mcDemo.calculateValue(2);
    }
}

Output

java.lang.ArithmeticException: / by zero
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:21)
java.lang.ArrayIndexOutOfBoundsException: 2
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:22)

Restriction with Multiple catch blocks in Java

When multiple catch statements are used, it is important to follow the order where the exception sub type is caught before any of their super type. Which means a catch block that catches an exception subclass must come before the catch clause that catches an exception super class.

As example – Exception class is super class and ArithmeticException is the child class so catch block for Exception class will catch an ArithmeticException too. Thus placing the catch block for Exception class before the catch block for ArithmeticException would mean that the catch block for ArithmeticException is never reached.

Note that in Java, unreachable code is an error so this situation will result in a compiler error.

Example

In the same code as used above if one more catch block for Exception is added as the first one, that will result in compiler error.

multiple catch blocks

That's all for this topic Multiple catch blocks in Java exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. Best practices for exception handling in Java
  2. Creating custom exception class
  3. throws clause
  4. try-with-resources in Java 7
  5. Java Exception Handling interview questions

You may also like -

No comments:

Post a Comment