Sub topic 13
When a switch throws MatchException
This chapter assumes you can read pattern switch expressions, sealed interfaces, and record patterns from the earlier chapters. You need JDK 21 or newer. The examples use only features that are final in Java 21.
Most pattern matching code never throws MatchException. The exception exists for two situations that the compiler cannot rule out in advance. Knowing both tells you whether a MatchException in your logs is a bug in your code, a build problem, or a bug in someone else's accessor.
What MatchException is
java.lang.MatchException is an unchecked exception. It extends RuntimeException and became final in Java 21. The Java language specification says a pattern match throws it when the match cannot complete normally and no other exception already describes the problem.
There are two causes:
- An exhaustive
switchfinds that no label matches the value at run time. - A record pattern calls an accessor method, and the accessor throws.
Everything else keeps its usual exception. The table shows where the boundary lies.
| Situation | What is thrown |
|---|---|
| Selector is `null` and there is no `case null` | `NullPointerException` |
| Exhaustive switch finds no matching label at run time | `MatchException` |
| A record accessor throws during deconstruction | `MatchException`, with the original exception as its cause |
| A `when` guard throws | The guard's own exception, unchanged |
| A switch statement over a non-sealed type has no matching case and is not required to be exhaustive | Nothing. Execution continues after the switch |
The null row is the one people confuse most often. A missing case null is not a matching failure. It is the same NullPointerException that switch has always thrown.
Cause 1: a switch that was exhaustive at compile time but not at run time
The compiler proves exhaustiveness against the class files it sees. The JVM later runs your switch against whatever classes are actually on the class path. If those two views differ, a value can arrive that no label covers.
For this to happen, the hierarchy must change after the switch was compiled. Typical triggers:
- A new permitted subtype is added to a sealed interface, and the switch's class is not recompiled.
- A new constant is added to an enum that a switch expression covers without
default. - A library you depend on ships a newer version of a sealed hierarchy than the one you compiled against.
Because the compiler inserts no default branch for you, it generates a final fallback. That fallback throws MatchException instead of letting the switch expression produce no value.
Reproducing it
Four source files are enough. The first version has two shapes.
// Shape.java
sealed interface Shape permits Circle, Square {}// Circle.java
record Circle() implements Shape {}// Square.java
record Square() implements Shape {}// Main.java
public class Main {
static String name(Shape shape) {
return switch (shape) {
case Circle c -> "circle";
case Square s -> "square";
};
}
public static void main(String[] args) throws Exception {
Shape shape = args.length == 0
? new Circle()
: (Shape) Class.forName(args[0])
.getDeclaredConstructor().newInstance();
System.out.println(name(shape));
}
}Main creates its shape by class name so that the same compiled Main can later receive a type it has never heard of. Compile everything and run it:
mkdir out
javac -d out Shape.java Circle.java Square.java Main.java
java -cp out MainThe output is circle. Now add a third shape. Change Shape.java to permit it:
// Shape.java (version 2)
sealed interface Shape permits Circle, Square, Triangle {}Add a new file:
// Triangle.java
record Triangle() implements Shape {}Recompile only these two files, leaving Main.class untouched, and run the old Main with the new type:
javac -cp out -d out Shape.java Triangle.java
java -cp out Main TriangleThe switch in Main.class was compiled when only two shapes existed. It now receives a Triangle and finds no label. The program fails with Exception in thread "main" java.lang.MatchException.
If you had recompiled Main.java as well, javac would have rejected the switch with "the switch expression does not cover all possible input values". That is the point of exhaustiveness checking: the error moves from run time to compile time, as long as everything is built together.
What the runtime check looks like
The diagram shows the path the generated code takes for a sealed switch with no default.
Cause 2: a record accessor that throws
A record pattern does not read fields directly. It calls the accessor method of each component, and a record is allowed to override its accessors. If one of them throws, the pattern match cannot finish. The language wraps that exception in a MatchException and keeps the original as the cause.
public class AccessorFailure {
record Ratio(int num, int den) {
public int den() {
if (den == 0) {
throw new IllegalStateException("zero denominator");
}
return den;
}
}
public static void main(String[] args) {
Object o = new Ratio(1, 0);
try {
if (o instanceof Ratio(var n, var d)) {
System.out.println(n + "/" + d);
}
} catch (MatchException e) {
System.out.println("MatchException, cause: " + e.getCause().getMessage());
}
}
}Running it prints MatchException, cause: zero denominator.
Two details matter here:
- The failure happens inside the pattern, before any branch body runs. Your
printlnis never reached. - A plain call such as
ratio.den()in ordinary code would throwIllegalStateExceptiondirectly. The wrapping applies only when the pattern calls the accessor on your behalf. This lets the language separate "my pattern could not be evaluated" from "my own code threw".
The same rule applies to instanceof patterns and to switch. It also applies to nested patterns: in Line(Point(var x, var y), var end), an accessor failure in Point surfaces as a MatchException for the whole match.
Guards are different
A when guard is ordinary code that you wrote in the case. If it throws, the exception is not wrapped.
static String check(Object o) {
return switch (o) {
case String s when Integer.parseInt(s) > 10 -> "big";
case String s -> "small";
default -> "other";
};
}Calling check("abc") throws NumberFormatException. It does not throw MatchException. The rule of thumb is that MatchException is reserved for failures of the matching machinery itself: no label fits, or a deconstruction call failed.
Null components are not a source of MatchException
Records can hold null in a component, and that does not by itself cause a failure. What happens depends on the nested pattern:
- A nested pattern that is total for the component type, such as
var xor the exact component type, matchesnull. - A nested pattern that is not total, such as
Circle cfor a component of typeShape, does not matchnull. The case simply fails to apply and the next case is tried.
Consider the Box<Shape> example from the unnamed patterns chapter:
record Box<T>(T content) {}
static String name(Box<Shape> box) {
return switch (box) {
case Box<Shape>(Circle _) -> "box holding a circle";
case Box<Shape>(var _) -> "box holding another shape";
};
}For new Box<Shape>(null), the first case does not match, because Circle _ is not total. The second case matches, because var _ is total. The result is box holding another shape, with no exception. A null box itself would throw NullPointerException, since the selector is null and no case null exists.
Deciding what to do about it
Treat a MatchException as a signal that something is wrong. It is rarely something to catch and handle.
- Missing label after a rebuild. Rebuild every module that switches over the changed hierarchy. The compiler will then list each switch that needs a new case. Check that your build tool recompiles dependents of a changed sealed type, and that your deployment does not mix versions of a library.
- Accessor failure. Fix the accessor or the invariant that lets the record reach a bad state. If accessors can legitimately fail, deconstruction is the wrong tool and you should call the accessor in ordinary code where you control the handling.
- Sealed types across a library boundary. If you publish a sealed hierarchy and expect to add subtypes later, consumers who write switches without
defaultwill break at run time when they upgrade without recompiling. Either document that the hierarchy is closed to extension, or choose an open hierarchy and require adefaultbranch.
Adding default to silence the problem has a cost. You lose the compile-time check that tells you about every switch to update when you add a subtype. Use default where you truly want a fallback behavior, and omit it where a new subtype should force you to revisit the code.
Summary of the failure modes
MatchExceptionhas two sources: no label matched an exhaustive switch at run time, or a record accessor threw during deconstruction.- The first source needs a hierarchy that changed after the switch was compiled. Rebuilding everything together turns it into a compile error.
- The second source wraps the accessor's exception as the cause. You can read it with
getCause(). - A
nullselector withoutcase nullgivesNullPointerException, and a throwing guard propagates its own exception.
Exercise
A switch expression over a sealed interface Event has cases for Login and Logout and no default. The team adds a third permitted subtype Timeout to Event and ships the updated Event and Timeout classes without recompiling the class that holds the switch. What happens when a Timeout instance reaches the switch, and what happens if the same switch receives null?
Show answer
The Timeout instance matches no label, so the compiler-generated fallback throws MatchException. The null value throws NullPointerException, because the switch has no case null. Recompiling the switch's class would instead make the compiler report that the switch does not cover Timeout.
Exercise
Given record Temp(double celsius) { public double celsius() { throw new UnsupportedOperationException(); } }, what is thrown by if (o instanceof Temp(var c)) { } when o is a Temp, and what is thrown by calling new Temp(1.0).celsius() directly?
Show answer
The instanceof pattern calls the accessor on your behalf, so the UnsupportedOperationException is wrapped in a MatchException whose cause is the original exception. The direct call is ordinary code, so it throws UnsupportedOperationException with no wrapping.