Java 7 gives you the ability to codify a single catch block to catch more than one type of exception. The purpose of this multi-catch feature is to reduce code duplication and reduce the temptation to catch overly broad exceptions (for instance, catch (Exception ex)).

This is the old way of doing things, where you catch both the exceptions separately if any only if you want to handle each one of them separately. If both the logic handling in catch block is same then its a redundancy.


Before JDK 7

Say below is the example snippet which is a way to handle the exception in a traditional way.

Listing-1: /src/com/mnkartik/feature3/Main.java
package com.mnkartik.feature3;

import java.io.IOException;
import java.sql.SQLException;

public class Main {

   public static void main(String[] args){

       try{
           copy();

       }catch (IOException ex){
           System.out.println(ex.getMessage());

       }catch (SQLException ex){
           System.out.println(ex.getMessage());
       }
   }

   static void copy() throws IOException, SQLException    {
       if (Math.random() < 0.5)
           throw new IOException("cannot copy to file");
       else
           throw new SQLException("cannot copy to database");
   }
}

Check out the catch block in the Listing-1, where for both the exceptions, the handling logic is the same, to print error message to the console. Just for easier interpretation, simple output message is used, but in real world the logic might be different.


From JDK 7 onwards

Listing-2: /src/com/mnkartik/feature3/Main.java
// new jdk 1.7 approach
// make sure compiler settings are set to 1.7
try{
   copy();
   
}catch (IOException | SQLException ex){
   System.out.println(ex.getMessage());            
}

From the Listing-2, this is a new way of handling exceptions, in jdk 7, which consolidate the common logic hanlding at one place. Check out the syntax ‘|’. The output of both will be the same.

NOTE: This new approach requires JDK 7 to be installed.

The only catch here is that, the exception parameter ‘ex’ (Listing-2) is of final type and cannot be assigned any other value, else error occurs as shown below. Rather specifically, it follows the rules of any other final variable in java.

image


Bytecode advantage

The bytecode resulting from compiling a catch block that handles multiple exception types will be smaller than compiling several catch blocks that each handle only one of the listed exception types. A catch block that handles multiple exception types contributes no duplicate bytecode during compilation. In other words, the bytecode doesn’t contain replicated exception handling logic.


Download Source Code Browse Source Code