Catching Multiple Exceptions in Java
The catch
clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|
).
try {
// ...
} catch (IOException | SQLException ex) {
logger.log(ex);
throw ex;
}
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 !!!
// ...
}
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.