orElseThrow() in Java
The orElseThrow() method in Java is a part of the java.util.Optional class
and its primary purpose is to retrieve the value contained within an Optional instance or, if no value is present, to throw an exception.
Get Articles Media’s stories in your inbox
Join Medium for free to get updates from this writer.
There are two main variations of orElseThrow():
public T orElseThrow():- This version returns the value if it’s present in the
Optional. - If the
Optionalis empty, it throws aNoSuchElementException. public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X:- This version also returns the value if present.
- If the
Optionalis empty, it uses the providedexceptionSupplierto create and throw a custom exception of typeX. This allows for more specific error handling than the defaultNoSuchElementException.
How it works:
Value Present:
- If the
Optionalobject contains a non-null value,orElseThrow()simply returns that value.
Value Not Present:
- If the
Optionalobject is empty (i.e., it doesn't contain a value),orElseThrow()will either throw aNoSuchElementException(in the no-argument version) or throw the exception generated by theexceptionSupplier(in the version with aSupplierargument).
Example:
Java
import java.util.Optional;
import java.util.NoSuchElementException;public class OptionalOrElseThrowExample {
public static void main(String[] args) {
Optional<String> presentOptional = Optional.of("Hello");
Optional<String> emptyOptional = Optional.empty(); // Using orElseThrow() with a present value
String value1 = presentOptional.orElseThrow();
System.out.println("Value from present Optional: " + value1); // Using orElseThrow() with a custom exception supplier
try {
String value2 = emptyOptional.orElseThrow(() -> new IllegalArgumentException("No value found in optional!"));
System.out.println("This won't be printed.");
} catch (IllegalArgumentException e) {
System.out.println("Caught custom exception: " + e.getMessage());
} // Using orElseThrow() on an empty Optional (throws NoSuchElementException)
try {
String value3 = emptyOptional.orElseThrow();
System.out.println("This also won't be printed.");
} catch (NoSuchElementException e) {
System.out.println("Caught default exception: " + e.getMessage());
}
}
}









