If you call
first() on a subject that isn't matched by a pattern -
thrown. We discussed that in the previous chapter.
But what if you expected the subject not to be matched? And how do you to react to it?
Optional matches with
findFirst() can be called with a callback (that accepts
Detail) just like
The difference is:
findFirst() never throws
SubjectNotMatchedException, and allows you to control an unmatched subject by
appropriate control methods:
If a match is found, then the result of
findFirst() callback is returned. If a match is not found, however, then the
handling of an unmatched subject relies in the chained method.
If a match is not found, it returns a default value.
If a match is not found, it calls
orElse() callback and uses it to evaluate a return value.
orElse() is called with
NotMatched, which contains only a handful of methods
If a match is not found, it throws
SubjectNotMatchedException by default.
Custom exceptions for
You can also supply your own exception class name.
Of course, your custom exception must meet certain requirements:
It has to be a class
Trying to instantiate interfaces or abstract classes would break our "Explicity rule" The class must be concrete and explicit.
It has to implement
It must have a suitable constructor
The class must be instantiable with one of the following signatures and parameter types.
$messagecan be a string
__construct($message, $subject), where
$subjectcan be strings
findFirst()->orThrow() without your custom exception is identical to
If you don't like functional programming style, you are free to use
(which throws an exception) and just catch it.