J.VII · Java 25 practice question

What happens when this Java 25 program is compiled and run?

int load() {
    throw new IllegalStateException("boom");
}
void main() {
    String res = switch (load()) {
        case 1 -> "one";
        default -> "other";
    };
    System.out.println(res);
}
Choose one answer
Check answer and explanation

Correct answer: It throws IllegalStateException directly from evaluating the selector expression

Explanation

It throws IllegalStateException directly from evaluating the selector expression because abrupt completion of the selector causes the entire switch expression to complete abruptly for the same reason.

Common trap

The default branch only handles normal selector values that do not match other labels, not exceptions thrown by the selector. MatchException is used for unhandled exhaustiveness gaps at run time, not for exceptions thrown during selector evaluation.

Source: JLS SE 25 §15.28.2. Run-Time Evaluation of switch Expressions
Checked against the cited text on 2026-11-25.

Report an error in this question