orElseThrowSupplier
orElseThrowSupplier is a term used to describe the practice of providing an exception to be thrown when an Optional is empty. It is not a separate API but relies on the exception-supplier argument of the Optional.orElseThrow method available in Java 8 and later. The orElseThrow method takes a Supplier<? extends Throwable> and, if the Optional has a value, returns that value; if empty, it invokes the supplier to obtain the exception to throw and propagates it.
Typical usage involves passing a lambda or method reference that constructs the desired exception. For example,
A common extension is to factor out exception construction into reusable suppliers to avoid duplicating messages.
Advantages of this approach include lazy construction of exceptions (the exception object is created only if
See also Optional.orElseThrow, Supplier, Java Optional.
---