Java 10 - Optional.orElseThrow
- schick09
- Dec 27, 2024
- 1 min read
Java 10 has added an interesting new method to the Optional class: Optional.orElseThrow(). The interesting part is, it's an exact duplicate of the
Optional.get() method. So what's the deal here? Why would you ever want to use this?
Well typically, we check whether or not an Optional has a value before we try to
retrieve (or Optional.get() ) that value. If you try an Optional.get() and there is no value, it will throw a NoSuchElementException.
Well let's suppose you're OK with that. You are planning to catch that exception and log a useful error message, for example.
That's why this method was created - just to be more intentional about the fact that you know retrieving the value from the Optional could throw a NoSuchElementException and you want your code to be self-documenting to that fact.
So yeah, it's a little strange. It really isn't anything new, functionality-wise. But it's something you can use to document the fact that this Optional retrieval is expected to throw a NoSuchElementException and I'm going to take action when that happens.
Onward and upward.

Comments