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 XParameters
| Parameter | Type | Description |
|---|---|---|
| exceptionSupplier | Supplier<? 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 7Notes
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
- Optional.orElse() — Returns the value, or a fallback if there is none.
- IllegalArgumentException — Signals that a method received an invalid argument.
- Optional.isPresent() — Checks whether an `Optional` holds a value.
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.