โ— Shell
clean mode source โ†—

Optional.orElseThrow() without supplier

Home / Errors / Optional.orElseThrow() without supplier

Code Comparison

// Risky: get() throws if empty, no clear intent
String value = optional.get();

// Verbose: supplier just for NoSuchElementException
String value = optional
    .orElseThrow(NoSuchElementException::new);
// 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()

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

Proof