Catching Multiple Exception Types in a single catch block in Java 7

Handling multiple exceptions prior to Java 7
Prior to Java 7, if one needed to have common handling for different type of exceptions, one needed to write duplicate code. I.e. one had to repeat the handling code to make it common across exception types. Given below is an example of such code –

catch (IOException ioex) {
 System.out.println("Error in System");
}catch (SQLException sqlex) {
 System.out.println("Error in System");

As you must have noticed in the above code that “Error in System” is repeated in both the catch blocks.

Handling multiple exceptions the Java 7 way
Java 7 now allows a single catch block to handle multiple exceptions. The syntax is as shown below –

catch (IOException|SQLException exception) {
 System.out.println("Error in System");

In the above Java 7 code the catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|). This feature reduces code duplication and lessen the temptation to catch an overly broad exception.

Important thing to note about handling multiple exceptions in a single catch block in Java 7

  1. If a catch block handles more than one exception type then the catch parameter is implicitly final. In this example, the catch parameter exception is final and therefore you cannot assign any values to it within the catch block.
  2. Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (hence superior) than the bytecode obtained by 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. Or, in other words, the bytecode has no replication of exception handlers.


Digiprove sealCopyright © 2014-2019, all rights reserved.