'Throw exception in optional in Java8
There is a method get(sql) (I can not modify it). This method returns MyObjects and it has to be in try catch block because JqlParseException is possible there. My code is:
String sql = something;
try{
MyObject object = get(sql);
} catch(JqlParseException e){
e.printStackTrace();
} catch(RuntimeException e){
e.printStackTrace();
}
I want to remove try catch and use Optional class, I tried:
MyObject object = Optional.ofNullable(get(sql)).orElseThrow(RuntimeException::new);
but IDE force there try catch too. And for:
MyObject object = Optional.ofNullable(get(sql)).orElseThrow(JqlParseException::new));
is an error (in IDE) The type JqlParseException does not define JqlParseException() that is applicable. Is there any way to avoid try catch blocks and use optional?
Solution 1:[1]
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.
Solution 2:[2]
Try this
Optional.ofNullable(result)
.orElseThrow(() -> new GenericClientException("Request body is not valid", HttpStatus.BAD_REQUEST));
Solution 3:[3]
if (StringUtils.isEmpty(message)) {
throw new ValidationException("empty message body received from the queue");
in java 8
Optional.ofNullable(message).filter(message -> !message.isEmpty()).orElseThrow(() -> new ValidationException("empty message body received from the queue")
);
Solution 4:[4]
Optional helps to deal with NullPointerException.
You can use it to cast new exceptions as mentioned.
MyObject object = Optional.ofNullable(get(sql)).orElseThrow(RuntimeException::new);
However, your method get(sql) is not returning NULL, which invalidates the use of OPTIONAL as desired.
I would keep using Try Catch.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | naveen reddy |
| Solution 3 | sudha mosalikanti |
| Solution 4 | Millys Carvalhaes |
