GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Optional.orElseThrow() without supplier | java.evolved
Errors
Beginner
Optional.orElseThrow() without supplierUse 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();
See a problem with this code? Let us know.
Why the modern way wins
📖
Self-documentingorElseThrow() clearly signals that absence is unexpected. 🔒
Avoids get()Static analysis tools flag get() as risky; orElseThrow() is idiomatic. ⚡
Less boilerplateNo 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
Proof
Related patterns
Errors
Beginner
Optional chainingJava 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");
JDK 9+
→
Streams
Intermediate
Optional.or() fallbackJava 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);
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"
);
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. |