我试图找出.orElseThrow在 Java Stream 中发生特定行为的原因。这个代码块
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)});
}
Run Code Online (Sandbox Code Playgroud)
导致此错误: unreported exception X; must be caught or declared to be thrown
我不想报告异常,因为这会导致我将其添加到与此交互的所有其他方法中。
但是,当我删除花括号 lambda 表达式时,只留下要抛出的新异常,如下所示:
private SomeContainer getSomeContainerFromList(SomeContainerList containerList, String containerId) {
return containerList.stream()
.filter(specificContainer -> specificContainer.getId().equals(containerId))
.findAny()
.orElseThrow(() -> new CustomInternalException("some special failure message"));
}
Run Code Online (Sandbox Code Playgroud)
它编译得很好,并且不再需要报告异常,但是,我无法在该.orElseThrow语句中记录消息或执行任何其他逻辑。
为什么会发生这种情况?我看到了一种类似的问题,它解释说这可能是 JDK 中的一个错误,但我想确保在我的情况下就是这种情况。