Zac*_*ach 6 java exception java-8 java-stream
我试图找出.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 中的一个错误,但我想确保在我的情况下就是这种情况。
Don\xe2\x80\x99t抛出异常,返回它:
\n\n.orElseThrow(() -> {\n String message = "some special failure message";\n log.error(message);\n // change \xe2\x80\x9cthrow\xe2\x80\x9d to \xe2\x80\x9creturn\xe2\x80\x9d:\n return new CustomInternalException(message)});\nRun Code Online (Sandbox Code Playgroud)\n\n.orElseThrow()接受 a Supplier<Exception>,它应该返回而不是抛出异常。
| 归档时间: |
|
| 查看次数: |
336 次 |
| 最近记录: |