I am trying to track down why a specific behavior is happening with .orElseThrow
in a Java Stream. This code block
private SomeContainer getSomeContainerFromList(SomeContainerList containerList, String containerId) {
return containerList.stream()
.filter(specificContainer -> specificContainer.getId().equals(containerId))
.findAny()
.orElseThrow(() -> {
String message = "some special failure message";
log.error(message);
throw new CustomInternalException(message)});
}
results in this error: unreported exception X; must be caught or declared to be thrown
I don't want to report the exception because that would cause me to add that to every other method who interacts with this.
However, when I remove the curly braced lambda expression, leaving just the new exception to be thrown, like so:
private SomeContainer getSomeContainerFromList(SomeContainerList containerList, String containerId) {
return containerList.stream()
.filter(specificContainer -> specificContainer.getId().equals(containerId))
.findAny()
.orElseThrow(() -> new CustomInternalException("some special failure message"));
}
It compiles just fine and the exception no longer needs to be reported, although, I can't log the message or do any other logic in that .orElseThrow
statement.
Why does this happen? I've seen a sort of similar question which explains that this could be a bug in the JDK but I want to make sure that is the case in my situation.
Don’t throw the exception, return it:
.orElseThrow(() -> {
String message = "some special failure message";
log.error(message);
// change “throw” to “return”:
return new CustomInternalException(message)});
.orElseThrow()
accepts a Supplier<Exception>
, which should return, rather than throw, an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With