Add a no-arg orElseThrow() method to java.util.Optional, OptionalDouble, OptionalInt, and OptionalLong.
Optional.get() is an "attractive nuisance" because the name "get" is quite an obvious name, and it ought to be frequently used. It's more often misused then used properly, and it's an outlier because unlike most other get() methods, it throws an exception if the Optional is empty. Since the point of Optional is to facilitate handling of the empty case, calling get() is often the wrong thing to do.
Introduce a new method orElseThrow() that is synonymous with get(): it retrieves the value if it's present, or it throws NoSuchElementException if empty. Adjust wording of the get() specification to state that orElseThrow() is preferred, but otherwise don't change semantics or behavior of get(). Corresponding changes for OptionalDouble, OptionalInt, and OptionalLong.
See attached specdiff.
- csr of
JDK-8140281 (opt) add no-arg orElseThrow() as preferred alternative to get()