Module java.base
Package java.lang

Class MatchException

All Implemented Interfaces:
Serializable

public final class MatchException extends RuntimeException
MatchException is a preview API of the Java platform.
Programs can only use MatchException when preview features are enabled.
Preview features may be removed in a future release, or upgraded to permanent features of the Java platform.
Thrown to indicate an unexpected failure in pattern matching.

MatchException may be thrown when an exhaustive pattern matching language construct (such as a switch expression) encounters a value that does not match any of the provided patterns at runtime. This can arise from a number of cases:

  • Separate compilation anomalies, where a sealed interface has a different set of permitted subtypes at runtime than it had at compilation time, an enum has a different set of constants at runtime than it had at compilation time, or the type hierarchy has changed in incompatible ways between compile time and run time.
  • null values and nested patterns using sealed types. If an interface or abstract class C is sealed to permit A and B, then the set of record patterns R(A a) and R(B b) are exhaustive on a record R whose sole component is of type C, but neither of these patterns will match new R(null).
  • Null targets and nested record patterns. Given a record type R whose sole component is S, which in turn is a record whose sole component is String, then the nested record pattern R(S(String s)) will not match new R(null).

Match failures arising from unexpected inputs will generally throw MatchException only after all patterns have been tried; even if R(S(String s)) does not match new R(null), a later pattern (such as R r) may still match the target.

MatchException may also be thrown when operations performed as part of pattern matching throw an unexpected exception. For example, pattern matching may cause methods such as record component accessors to be implicitly invoked in order to extract pattern bindings. If these methods throw an exception, execution of the pattern matching construct may fail with MatchException. The original exception will be set as a cause of the MatchException. No suppressed exceptions will be recorded.

See Java Language Specification:
14.11.3 Execution of a switch Statement
14.30.2 Pattern Matching
15.28.2 Run-Time Evaluation of switch Expressions
Since:
19
See Also:
  • Constructor Details

    • MatchException

      public MatchException(String message, Throwable cause)
      Constructs an MatchException with the specified detail message and cause.
      Parameters:
      message - the detail message (which is saved for later retrieval by the Throwable.getMessage() method).
      cause - the cause (which is saved for later retrieval by the Throwable.getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)