Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Wednesday, February 12, 2014

Handling multiple exceptions in a single catch block: Java 1.7 update


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.

Consider the following example, which contains duplicate code in each of the catch blocks:

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

In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.The following example, which is valid in Java SE 7 and later,eliminates the duplicated code:

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


The catch clause specifies the types of exceptions that the block
can handle,and each exception type is separated with a vertical bar (|).

Note: If a catch block handles more than one exception type,then the catch parameter is implicitly final.

In this example, the catch parameter ex is final and therefore you

cannot assign any values to it within the catch block.

Advantage of this update: Byte code 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.

catch block that handles multiple exception types creates no duplication in the byte code generated by the compiler;the byte code has no replication of exception handlers.

No comments: