Optional get can throw
Calling Optional.get without checking presence turns a missing value into NoSuchElementException. Prefer orElse, orElseGet, orElseThrow with a meaningful exception.
Optional.orElseThrow()with no arguments (Java 10+) is the shorter equivalent ofget, and it throwsNoSuchElementException. Other platform gotchas welcome in the comments.Calling get on an empty Optional throws NoSuchElementException, a runtime error that hides the missing-value case. Use orElse, orElseGet, or orElseThrow with a message describing the absence.
get assumes a value is present and fails loudly when it is not, which is often a missing check rather than an intended crash. Choosing orElseThrow with a descriptive exception documents the expectation.
"Optional get can throw" is a useful thing to know about with java / optional. Thanks for sharing it.
Without an isPresent check, a missing result becomes NoSuchElementException at the call site. The alternatives are orElse, orElseGet, or orElseThrow, each of which states the fallback explicitly.
Specific and to the point: "Optional get can throw". Worth a look if you touch java / optional.
Appreciate the write-up on "Optional get can throw". Useful for anyone using java / optional.
"Optional get can throw" is a useful thing to know about with java / optional. Thanks for sharing it.
Good to see "Optional get can throw" written down. Handy reference for anyone working with java / optional.