In Java 10, the Optional.orElseThrow() method was enhanced to become the preferred method for retrieving a value from an Optional when the value is present, and throwing an exception otherwise. Let’s explore how this works.
Enhanced Optional.orElseThrow()
Prior to Java 10, the Optional class provided:
orElse()– Retrieves the value if present or returns a default value.orElseGet()– Retrieves the value or calculates one using a supplier.orElseThrow(Supplier<? extends X> exceptionSupplier)– Retrieves the value or throws the exception provided by the supplier.
With Java 10, the Optional.orElseThrow() now acts as a shorthand for orElseThrow(NoSuchElementException::new) when you need to retrieve a value, and throw an exception if the value is absent, without providing a custom exception supplier.
Usage
Key Behavior:
- If the
Optionalcontains a value,orElseThrow()will return the value. - If the
Optionalis empty, it will throw aNoSuchElementException.
Example Code:
package org.kodejava.util;
import java.util.NoSuchElementException;
import java.util.Optional;
public class EnhancedOptionalExample {
public static void main(String[] args) {
// An Optional with a value
Optional<String> optionalWithValue = Optional.of("Hello, Java 10!");
// Retrieve the value using orElseThrow()
String value = optionalWithValue.orElseThrow();
System.out.println("Value: " + value); // Output: Hello, Java 10!
// An empty Optional
Optional<String> emptyOptional = Optional.empty();
try {
// Attempt to retrieve the value from an empty Optional
emptyOptional.orElseThrow();
} catch (NoSuchElementException e) {
System.err.println("Caught Exception: " + e.getMessage()); // Output: No value present
}
}
}
Comparison with Other Optional Methods
| Method | Behavior |
|---|---|
orElse(value) |
Returns the value if present; otherwise, returns the provided default value. |
orElseGet(supplier) |
Returns the value if present; otherwise, computes a value using the supplier. |
orElseThrow(supplier) |
Returns the value if present; otherwise, throws an exception provided by the supplier. |
orElseThrow() |
(Java 10) Returns the value if present; otherwise, throws a NoSuchElementException (default). |
Advantages of Enhanced orElseThrow()
- Simplicity: Eliminates the need to write
orElseThrow(NoSuchElementException::new)explicitly. - Readability: Makes the code concise and expressive.
- Standardized Exception: Default exception (
NoSuchElementException) aligns with the semantics of an emptyOptional.
Real-World Use Case
A common scenario is when processing data that is expected to be present:
Example:
Optional<String> username = fetchUsernameFromDatabase();
String verifiedUsername = username.orElseThrow();
System.out.println("Verified Username: " + verifiedUsername);
Here, if the username is absent, the application will throw a runtime exception (NoSuchElementException), indicating data inconsistency.
The enhanced Optional.orElseThrow() introduced in Java 10 simplifies handling Optional objects by providing a default exception mechanism without needing a custom supplier.
