orElseThrow: Throwing When Empty
What you'll learn: How to use orElseThrow() to explicitly signal that an absent value is an error condition requiring immediate attention.
When Absence Is Actually an Error
You've seen orElse() and orElseGet() for providing fallback values when an Optional is empty. But sometimes an empty Optional isn't a scenario you can gracefully handle—it's a programming error or an unexpected state that should halt execution.
That's where orElseThrow() comes in.
The Purpose of orElseThrow()
When you call orElseThrow() on an empty Optional, it throws a NoSuchElementException. This explicitly communicates: "I expected this value to exist, and if it doesn't, something has gone seriously wrong."
Think of it like this: If you order a package that's supposed to contain a gift, orElse() gives you a backup gift, orElseGet() makes a new gift on the spot—but orElseThrow() raises an alarm because someone failed to pack the gift at all.
Basic Syntax
Optional<String> userName = getUserName(userId);
String name = userName.orElseThrow(); // Throws NoSuchElementException if empty
If userName contains a value, you get that value. If it's empty, you get an exception with the message "No value present."
Why Use This Over get()?
You already learned that get() is dangerous because it throws the same exception but hides your intent. With orElseThrow(), you're explicitly stating: "I know this might be empty, but that would be exceptional." It makes code reviews easier and your intentions crystal clear.
Key Takeaway: Use orElseThrow() when an empty Optional represents a bug or unrecoverable error condition—it throws NoSuchElementException while clearly signaling that absence is exceptional, not normal.