首頁  >  文章  >  Java  >  在 Java 8 中將 Lambda 表達式與流結合使用時如何處理檢查異常?

在 Java 8 中將 Lambda 表達式與流結合使用時如何處理檢查異常?

DDD
DDD原創
2024-10-27 05:06:30994瀏覽

How to Handle Checked Exceptions When Using Lambda Expressions with Streams in Java 8?

Java 8:Lambda 流,透過異常處理方法進行過濾

在Java 8 中,流中的lambda 表達式可以有效地過濾元素。但是,在處理拋出 IOException 等已檢查異常的方法時,可能會出現複雜情況。

以下程式碼片段示範了此問題:

<code class="java">class Bank {
    public Set<String> getActiveAccountNumbers() throws IOException {
        Stream<Account> s = accounts.values().stream();
        s = s.filter(a -> a.isActive());
        Stream<String> ss = s.map(a -> a.getNumber());
        return ss.collect(Collectors.toSet());
    }
}
interface Account {
    boolean isActive() throws IOException;
    String getNumber() throws IOException;
}</code>

此程式碼無法編譯,因為它無法處理lambda 表達式中的 isActive 和 getNumber 方法拋出 IOException。

要解決此問題,我們需要在異常轉義lambda 之前捕獲該異常:

<code class="java">s = s.filter(a -> {
    try {
        return a.isActive();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
});</code>

當lambda 被評估時在未聲明受檢異常的不同上下文中,我們將受檢異常包裝在未檢測異常。

或者,您可以使用一種方法來消除編譯器的異常檢查:

<code class="java">return s.filter(a -> uncheckCall(a::isActive))
        .map(Account::getNumber)
        .collect(toSet());</code>

其中uncheckCall 定義為:

<code class="java">public static <T> T uncheckCall(Callable<T> callable) {
    try {
        return callable.call();
    } catch (Exception e) {
        sneakyThrow(e);
        return null; // Unreachable but needed to satisfy compiler
    }
}</code>

此方法有效地將已檢查的異常轉換為未檢查的異常。但是,應謹慎使用,因為如果處理不當,可能會導致意外行為。

以上是在 Java 8 中將 Lambda 表達式與流結合使用時如何處理檢查異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn