Java 25 (LTS) reference · Optional
Java Optional orElseThrow() Method
Return the value if present, otherwise throw: NoSuchElementException by default, or an exception you supply.
Java 25 (LTS) Since Java 10
Syntax
optional.orElseThrow(exceptionSupplier)
Parameters
| Parameter | Description |
|---|---|
exceptionSupplier optionalSupplier<X> |
Creates the exception to throw. |
Return value
The value.
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, String> users = Map.of(1, "Ana");
String name = Optional.ofNullable(users.get(1)).orElseThrow();
System.out.println(name);
}
}
Output
Ana
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, String> users = Map.of(1, "Ana");
try {
Optional.ofNullable(users.get(9)).orElseThrow(() -> new IllegalArgumentException("user 9 not found"));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Output
user 9 not found
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 10 | Added |
Related
optional.orElse()· Return the value if present, otherwise a default. orElseGet() computes the default lazily, only when needed.- Java Optional · tutorial