Throw exception in optional in Java8
Optional
is not intended for the purpose of dealing with exceptions, it was intended to deal with potential null
s without breaking the flow of your program. For example:
myOptional.map(Integer::parseInt).orElseThrow(() -> new RuntimeException("No data!");
This will automatically skip the map
step if the optional was empty and go right to the throw
step -- a nice unbroken program flow.
When you write:
myOptionalValue.orElseThrow(() -> new RuntimeException("Unavailable"));
... what you are really saying is: Return my optional value, but throw an exception if it is not available.
What you seem to want is a way to create an optional (that instantly catches the exception) and will rethrow that exception when you try using the optional.
That's not how Optionals work. They don't make try-catch-blocks obsolete. However, you could introduce a new wrapper-function like this:
public Optional<MyObject> getMyObject(final String jql) {
try {
return Optional.ofNullable(get(sql));
} catch (final JqlParseException e) {
return Optional.empty();
}
}
You won't have to deal with the exception anymore, but you won't know if there was an error if you get an empty Optional as well.
Try this
Optional.ofNullable(result)
.orElseThrow(() -> new GenericClientException("Request body is not valid", HttpStatus.BAD_REQUEST));