GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Optional.orElseThrow() without supplier | java.evolved

Home / Errors / Optional.orElseThrow() without supplier
Errors Beginner

Optional.orElseThrow() without supplier

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

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

Optional Null Safety Exception Handling
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();
Share 𝕏
See a problem with this code? Let us know.
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
Optional.orElseThrow() ↗
Proof
View proof source ↗
Related patterns
Errors Beginner

Optional chaining

Java 8
String city = null;
if (user != null) {
    Address addr = user.getAddress();
    if (addr != null) {
        city = addr.getCity();
    }
}
if (city == null) city = "Unknown";
Java 9+
String city = Optional.ofNullable(user)
    .map(User::address)
    .map(Address::city)
    .orElse("Unknown");
Hover to see modern ➜
JDK 9+ →
Streams Intermediate

Optional.or() fallback

Java 8
Optional<Config> cfg = primary();
if (!cfg.isPresent()) {
    cfg = secondary();
}
if (!cfg.isPresent()) {
    cfg = defaults();
}
Java 9+
Optional<Config> cfg = primary()
    .or(this::secondary)
    .or(this::defaults);
Hover to see modern ➜
JDK 9+ →
Errors Beginner

Objects.requireNonNullElse()

Java 8
String name = input != null
    ? input
    : "default";
// easy to get the order wrong
Java 9+
String name = Objects
    .requireNonNullElse(
        input, "default"
    );
Hover to see modern ➜
JDK 9+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.