Thursday, December 12, 2019

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 more than one type of exception in 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 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

Specifying two or more exceptions of the same hierarchy in the multi-catch statement will result in compile time error.
As example- Following catch statement will give compiler error because FileNotFoundException is a subtype of the IOException class.

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

Or the following statement, which will also result 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.

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html

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 Exception Handling
  2. Multiple Catch Blocks in Java Exception Handling
  3. Difference Between Checked & Unchecked Exception in Java
  4. Difference Between throw And throws in Java Exception Handling
  5. final Vs finally Vs finalize in Java

You may also like-

  1. Java pass by value or pass by reference
  2. Why file name and class name should be same in Java
  3. Marker interface in Java
  4. Difference Between Abstract Class And Interface in Java
  5. BigDecimal in Java
  6. Why wait(), notify() and notifyAll() methods are in Object class
  7. Deadlock in Java multi-threading
  8. Stream API in Java 8