Thursday, March 7, 2024

Multi-Catch Statement in Java Exception Handling

There has always been criticism of checked exceptions in Java exception handling for being verbose and cluttering the code with try-catch blocks.
In Java 7 two new features- try-with-resources (Automatic resource management) and multi-catch statement have been added to mitigate that problem to certain extent.

In this post we'll talk about multi-catch statement in Java exception handling along with examples to see how to handle multiple exceptions in a single catch block using multi-catch statement.

Handling more than one type of exception without multi-catch statement

Before Java 7 multi-catch statement, if two or more exceptions were handled in the same way, we still had to write separate catch blocks for handling them.

catch(IOException exp){
  logger.error(exp);
  throw exp;
}catch(SQLException exp){
  logger.error(exp);
  throw exp;
}

It can be noted here that; though the catch blocks are having the same exception handling code, it is difficult to create a common catch block to eliminate duplicate code because variable exp has different types in both of the catch block.

Java multi-catch - Handling more than one type of exception

Java 7 onward it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Each exception type within the multi-catch statement is separated by a pipe symbol (|).

catch(IOException | SQLException exp){
  logger.error(exp);
  throw exp;
}

Note that if a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter exp is final therefore you cannot assign any values to it within the catch block.

Java Multi-catch statement means better code

According to JavaDoc- "Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers."

Multi-catch statement & Exception hierarchy

While using multi-catch statement you will have to keep in mind the following rule.

If you specify two or more exceptions of the same hierarchy in the multi-catch statement, it will result in compile time error.
For example, following catch statement gives compiler error because FileNotFoundException is a subtype of the IOException class.

catch (FileNotFoundException | IOException ex) {    
 Logger.error(ex);   
}

Or the following statement, which also results in compile time error as Exception is super type of both ArithmeticException and ArrayIndexOutOfBoundsException.

// This will give compiler error
catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException ex){
  ex.printStackTrace();
}

Points to note

  1. With multi-catch statement in Java it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code.
  2. Each exception type within the multi-catch statement is separated by Pipe symbol (|).
  3. Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each.
  4. Specifying two or more exceptions of the same hierarchy in the multi-catch statement will result in compile time error.

That's all for this topic Multi-Catch Statement in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Try-With-Resources in Java With Examples
  2. Multiple Catch Blocks in Java Exception Handling
  3. Difference Between Checked And Unchecked Exceptions in Java
  4. Difference Between throw And throws in Java
  5. final Vs finally Vs finalize in Java

You may also like-

  1. Java Pass by Value or Pass by Reference
  2. Why Class Name And File Name Should be Same in Java
  3. Marker Interface in Java
  4. Difference Between Abstract Class And Interface in Java
  5. BigDecimal in Java With Examples
  6. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  7. Deadlock in Java Multi-Threading
  8. Java Stream API Tutorial

3 comments:

  1. It's a good explanation of multi-catch statement. In fact I found it better than many other resources I have been reading. Thanks for that.

    ReplyDelete
  2. "In multi-catch statement make sure that you go from subtype exception class to parent exception classes otherwise there will be a compilation error."

    Please check if this statement holds valid. If I declare the following, still I would get error.
    catch(ArithmeticException | Exception ex){
    ex.printStackTrace();
    }

    ReplyDelete
  3. Thanks for pointing it out, you are right the second statement holds true - Specifying two or more exceptions of the same hierarchy in the multi-catch statement will result in compile time error.

    ReplyDelete