- All Implemented Interfaces:
Serializable
MatchException
is a preview API of the Java platform.
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 classC
is sealed to permitA
andB
, then the set of record patternsR(A a)
andR(B b)
are exhaustive on a recordR
whose sole component is of typeC
, but neither of these patterns will matchnew R(null)
.- Null targets and nested record patterns. Given a record type
R
whose sole component isS
, which in turn is a record whose sole component isString
, then the nested record patternR(S(String s))
will not matchnew 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 Summary
ConstructorDescriptionMatchException
(String message, Throwable cause) Constructs anMatchException
with the specified detail message and cause. -
Method Summary
Methods declared in class java.lang.Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
-
Constructor Details
-
MatchException
Constructs anMatchException
with the specified detail message and cause.- Parameters:
message
- the detail message (which is saved for later retrieval by theThrowable.getMessage()
method).cause
- the cause (which is saved for later retrieval by theThrowable.getCause()
method). (Anull
value is permitted, and indicates that the cause is nonexistent or unknown.)
-
MatchException
when preview features are enabled.