Optional.orElseThrow() without supplier
Use Optional.orElseThrow() as a clearer, intent-revealing alternative to get().
Code Comparison
✕ Java 8
// Risky: get() throws if empty, no clear intent
String value = optional.get();
// Verbose: supplier just for NoSuchElementException
String value = optional
.orElseThrow(NoSuchElementException::new);
✓ Java 10+
// Clear intent: throws NoSuchElementException if empty String value = optional.orElseThrow();
Why the modern way wins
Self-documenting
orElseThrow() clearly signals that absence is unexpected.
Avoids get()
Static analysis tools flag get() as risky; orElseThrow() is idiomatic.
Less boilerplate
No need to pass a supplier for the default NoSuchElementException.
Old Approach
get() or orElseThrow(supplier)
Modern Approach
orElseThrow()
Since JDK
10
Difficulty
beginner
JDK Support
Optional.orElseThrow() without supplier
Available
Available since JDK 10 (March 2018).
How it works
Optional.get() is widely considered a code smell because it hides the possibility of failure. The no-arg orElseThrow(), added in Java 10, does exactly the same thing but makes the intent explicit: the developer expects a value and wants an exception if absent.
Related Documentation