All 15 Exceptions questions
More in Exceptions
Advertisement
Back to results for “Java Fundamentals: Syntax”
Java › Exceptions

What is the multi-catch syntax (catch (IOException | SQLException e)) introduced in Java 7, and what restriction applies to the exception types combined in a single multi-catch block?

Intermediate

Answer

Multi-catch lets a single catch block handle multiple, unrelated exception types with identical handling logic, avoiding duplicated catch blocks with the exact same body for each type -- the restriction is that the combined exception types must not be related by a subclass/superclass relationship (catching both a specific exception AND its own supertype together in the same multi-catch is redundant and rejected by the compiler), and the resulting caught variable is implicitly treated as the most specific common supertype of the listed types (and effectively final, so it can't be reassigned within the catch block).
try {
    riskyIOOperation();
    riskyDatabaseOperation();
} catch (IOException | SQLException e) {
    // shared handling logic for both, avoiding duplicated catch blocks
    log.error("Operation failed", e);
    throw new ServiceException("Operation failed", e);
}
// e's static type here is Exception (the nearest common supertype of IOException and SQLException)
Real-world example A method that can fail with either an IOException or a SQLException, but wants identical error-logging-and-wrapping behavior for both, uses multi-catch to consolidate what would otherwise be two nearly-identical catch blocks into one, reducing code duplication while still only catching the specific types actually expected.

Common follow-ups: Why does the compiler reject combining a supertype and its own subtype together in a multi-catch?;How does the caught variable's static type get determined when the combined exception types don't share an obvious common ancestor beyond Exception?