EMZETT.
Login

Multiple Exceptions

In short: Several catch blocks (or one combined block with |) after a try, to handle different types of error differently.

In more detail: The order matters: more specific exception types have to come before more general types, otherwise an earlier, broader catch block (e.g. Exception) catches everything and the more specific one after it is never reached — the compiler reports this as an error. With catch (IOException | SQLException e), several types handled identically can be combined in one block.

In Depth

try {
    int[] numbers = {1, 2, 3};
    int result = 10 / numbers[5]; // throws ArrayIndexOutOfBoundsException, not ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Arithmetic error: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Invalid index: " + e.getMessage());
} catch (Exception e) { // catch-all for EVERYTHING else - must come last
    System.out.println("Unexpected error: " + e.getMessage());
}
 
// Combined multi-catch (since Java 7) - identical handling for several types
try {
    // ... code that can throw IOException or SQLException
} catch (IOException | SQLException e) {
    System.out.println("File or database error: " + e.getMessage());
    // e here effectively has the type "IOException or SQLException" - only shared methods usable
}

The compiler enforces a specific order for catch blocks: since ArithmeticException and ArrayIndexOutOfBoundsException are both subclasses of Exception, a catch (Exception e) BEFORE the more specific blocks would catch all errors and the more specific blocks would become unreachable, dead code — Java therefore reports this as a compile error (“exception has already been caught”), not just as a runtime surprise. Multi-catch (|) is worthwhile when several independent exception types are meant to be handled exactly the same way — within the block, the exception variable’s type is then restricted to the shared intersection of methods of both (or several) types.

See also: Exceptions, Error Codes