JDK-8140281 : (opt) add no-arg orElseThrow() as preferred alternative to get()
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util
  • Priority: P3
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2015-10-21
  • Updated: 2018-02-15
  • Resolved: 2017-12-14
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 10
10 b36Fixed
Related Reports
CSR :  
Relates :  
Relates :  
Sub Tasks
JDK-8197978 :  
Description
Optional.get() is an "attractive nuisance" and is too tempting for programmers, leading to frequent errors. People don't expect a getter to throw an exception. A replacement API for Optional.get() with equivalent semantics should be added. The specification for Optional.get() should direct readers to the new API. However, Optional.get() shouldn't be deprecated just yet; deprecation is covered by the follow-on issue JDK-8160606.

The current proposal for replacement is a no-arg Optional.orElseThrow(). This fits well within the family of or-else methods, and it's closely related to orElseThrow(exSupplier), as if providing a NoSuchElementException supplier as a default.
Comments
Review thread of updated proposal: http://mail.openjdk.java.net/pipermail/core-libs-dev/2017-December/050465.html
2017-12-08

A previous proposal for replacement is Optional.getWhenPresent(). This name reinforces the assumption the caller is making, namely that the value is present. However, the "when" seemed to connote time, not the notion of definiteness, misleading people into thinking that it did something like blocking until a value was present. Alternatives include getOrThrow() and orElseThrow(). Previous review thread of proposal that included deprecation of Optional.get(): http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html
2017-12-08