簡體   English   中英

Java8 Stream .orElseThrow 未報告的異常錯誤

[英]Java8 Stream .orElseThrow unreported exception error

我試圖.orElseThrow在 Java Stream 中使用.orElseThrow發生特定行為的原因。 這個代碼塊

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)});
}

導致此錯誤: unreported exception X; must be caught or declared to be thrown 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"));
}

它編譯得很好,並且不再需要報告異常,但是,我無法在該.orElseThrow語句中記錄消息或執行任何其他邏輯。

為什么會發生這種情況? 我看到了一種類似的問題,它解釋說這可能是 JDK 中的一個錯誤,但我想確保在我的情況下就是這種情況。

不要拋出異常,返回它:

.orElseThrow(() -> {
    String message = "some special failure message";
    log.error(message);
    // change “throw” to “return”:
    return new CustomInternalException(message)});

.orElseThrow()接受一個Supplier<Exception> ,它應該返回一個異常,而不是拋出一個異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM