Home

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.

---

optional.orElseThrow(()
->
new
NoSuchElementException("Value
not
present")).
This
pattern
is
often
referred
to
as
orElseThrowSupplier
because
the
lambda
acts
as
a
supplier
of
the
exception
to
throw.
For
instance,
static
Supplier<IllegalArgumentException>
missingValue(String
field)
{
return
()
->
new
IllegalArgumentException(field
+
"
is
missing");
}
then
optional.orElseThrow(missingValue("name")).
When
using
a
checked
exception,
the
type
parameter
of
orElseThrow
must
be
coordinated
with
the
throwing
method’s
signature,
since
orElseThrow
declares
it
can
throw
a
checked
Throwable.
needed)
and
clear
separation
between
presence
checks
and
error
handling.
Limitations
include
the
need
to
manage
exception
types
and
the
potential
confusion
of
readers
unfamiliar
with
the
supplier
pattern.