Errors beginner

Optional.orElseThrow() without supplier

Use Optional.orElseThrow() as a clearer, intent-revealing alternative to get().

✕ 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();
📖

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
Optional.orElseThrow() without supplier
Available

Available since JDK 10 (March 2018).

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.

Share 𝕏 🦋 in