Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 Stream .orElseThrow unreported exception error

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.

like image 979
Zach Avatar asked Feb 07 '20 21:02

Zach


1 Answers

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.

like image 91
Bohemian Avatar answered Nov 19 '22 01:11

Bohemian