1.4.  Use multi-catch in exception statements

[Note]

In Java SE 7, 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:

try {
    // ...
} 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, eliminates the duplicated code:

try {
    // ...
} 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: An exception can not be a subtype or supertype of one of the catch clause's exception parameters, otherwise code will not compile:

try (DataOutputStream out = new DataOutputStream(new FileOutputStream("data"))) {
    out.writeUTF("Hello");
} catch (FileNotFoundException | IOException  e) { // COMPILATION FAILS !!!
    // ...
}
					

public class FileNotFoundException extends IOException {
    // ...
}
					

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:

try (DataOutputStream out = new DataOutputStream(new FileOutputStream("data"))) {
    out.writeUTF("Hello");
} catch (RuntimeException | IOException  e) {
    e = new Exception(); // COMPILATION FAILS !!! (The e is final)
}
					

Bytecode 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. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide