102016May

Catching Multiple Exceptions In One Catch Block In Java

Java 7 New Feature

Writing same logic in every catch block is very tedious job and it also not good for readability of the Java program. In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Prior to Java 7

catch (IOException ex) {
logger.log(ex);
throw ex;
catch (SQLException ex) {
logger.log(ex);
throw ex;
}

In Java 7

catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}

Pipe (|) is use to separate multiple exceptions in single catch block. Also the parameter ex in catch block is final here and value can not assign to it.