Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Multi-catch: shared exception handling

The catch (A | B e) syntax handles different exception types in one block. Alternative types must not have a subtype relationship, and the parameter e is implicitly final.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

try {
    // operation
} catch (A | B e) {
    // shared handler
}

catch (A | B e) provides one handler for exceptions of type A or B, including their subtypes. | separates alternatives; it is not a bitwise operator here. e represents one caught exception, not a collection.

Alternatives must be exception classes and must not be subtypes of each other. Thus, catch (Exception | RuntimeException e) is a compile-time error.

The parameter e is implicitly final: it cannot be reassigned. Its declared type is the least upper bound (lub) of the alternative types, which determines the available members.

The example exercises both paths and expects A, then B. Share a handler when handling is identical; otherwise, use separate catch clauses.

Examples

public class MultiCatchDemo {
    static class A extends Exception {}
    static class B extends Exception {}

    static void fail(boolean first) throws A, B {
        if (first) {
            throw new A();
        }
        throw new B();
    }

    public static void main(String[] args) {
        for (boolean first : new boolean[] {true, false}) {
            try {
                fail(first);
            } catch (A | B e) {
                System.out.println(e.getClass().getSimpleName());
            }
        }
    }
}

Result

A
B

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources