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:
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: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.
A 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:
Post a Comment