Java Optional orElseThrow() Method
Example
Throw an exception when there is no name, and catch it:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> noName = Optional.empty();
try {
String name = noName.orElseThrow(() -> new IllegalStateException());
System.out.println(name);
} catch (IllegalStateException e) {
System.out.println("Error: there is no name.");
}
}
}
Definition and Usage
The orElseThrow() method returns the value in the Optional. If the Optional is empty, it throws an exception.
You choose the exception with a lambda expression (a short block of code that works like a method) that creates it, for example () -> new IllegalStateException(). Use it when a missing value is an error in your program.
Syntax
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
T refers to the data type of the value in the Optional. X refers to the type of the exception.
Parameter Values
| Parameter | Description |
|---|---|
| exceptionSupplier | Required. A Supplier object or lambda expression with no parameters, that creates the exception to throw. |
Technical Details
| Returns: | The value, if there is one. |
|---|---|
| Throws: | X - the exception that exceptionSupplier creates, if the Optional is empty. |
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods