Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Optional.orElseThrow()

Returns the value or throws an exception if there is none.

Available since: Java 10

Syntax

T orElseThrow()
<X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X

Parameters

ParameterTypeDescription
exceptionSupplierSupplier<? extends X>Optional: creates the exception for the empty case (Java 8).

Return value

TThe value from the `Optional`.

Examples

A custom exception with a clear message:

record User(int id, String name) {}
 
User findUser(int id) {
    return Stream.of(new User(1, "Anna"), new User(2, "Oleg"))
        .filter(u -> u.id() == id)
        .findFirst()
        .orElseThrow(() -> new IllegalArgumentException("No user with id " + id));
}
 
void main() {
    IO.println(findUser(2).name());
    try {
        findUser(7);
    } catch (IllegalArgumentException e) {
        IO.println(e.getMessage());
    }
}

Output:

Oleg
No user with id 7

Notes

The no-argument version (Java 10) throws NoSuchElementException with the message No value present and does the same as get(), but with a clearer name. Use it when a missing value means a bug.

See also

In the tutorial

  • Optional — The Optional class in Java: a value that may be absent, creating it with of and empty, orElse, map, ifPresent and orElseThrow.

Thanks for reading!

Donate to the site — we work hard for you.