java - 在没有 try-catch 的情况下处理 lambda 中的异常

标签 java lambda exception-handling java-8

据我所知,如果 lambda 实现的抽象方法的签名中没有 throws,则无法处理 lambda 中抛出的异常。

我遇到了以下代码,它有效。为什么 openStream() 不需要处理 IOException?我可以在 tryWithResources 中看到 try-catch 但我不明白它背后的机制。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.Function;
import java.util.function.Supplier;

public class Main {

    public static <AUTOCLOSEABLE extends AutoCloseable, OUTPUT> Supplier<OUTPUT> tryWithResources(
            Callable<AUTOCLOSEABLE> callable, Function<AUTOCLOSEABLE, Supplier<OUTPUT>> function,
            Supplier<OUTPUT> defaultSupplier) {
        return () -> {
            try (AUTOCLOSEABLE autoCloseable = callable.call()) {
                return function.apply(autoCloseable).get();
            } catch (Throwable throwable) {
                return defaultSupplier.get();
            }
        };
    }

    public static <INPUT, OUTPUT> Function<INPUT, OUTPUT> function(Supplier<OUTPUT> supplier) {
        return i -> supplier.get();
    }

    public static void main(String... args) {
        Map<String, Collection<String>> anagrams = new ConcurrentSkipListMap<>();
        int count = tryWithResources(
                () -> new BufferedReader(new InputStreamReader(
                        new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").openStream())),
                reader -> () -> reader.lines().parallel().mapToInt(word -> {
                    char[] chars = word.toCharArray();
                    Arrays.parallelSort(chars);
                    String key = Arrays.toString(chars);
                    Collection<String> collection = anagrams.computeIfAbsent(key, function(ArrayList::new));
                    collection.add(word);
                    return collection.size();
                }).max().orElse(0), () -> 0).get();
        anagrams.values().stream().filter(ana -> ana.size() >= count).forEach((list) -> {
            for (String s : list)
                System.out.print(s + " ");
            System.out.println();
        });
    }
}

最佳答案

我已将您的示例简化为核心部分:

public static void main(String[] args) {
    withCallable(() -> new URL("url").openStream()); // compiles
    withSupplier(() -> new URL("url").openStream()); // does not compile
}

public static <T> void withCallable(Callable<T> callable) { }

public static <T> void withSupplier(Supplier<T> callable) { }

如果您尝试这样做,您会发现 withCallable 可以正常编译,但 withSupplier 无法编译;即使 lambda 表达式与两个功能接口(interface)的签名兼容。

这背后的原因是 Callable 的功能方法接口(interface),即call() , 在其签名中声明 throws ExceptionSupplier.get()没有。

引用 JLS section 11.2.3 :

It is a compile-time error if a lambda body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the throws clause of the function type targeted by the lambda expression.

关于java - 在没有 try-catch 的情况下处理 lambda 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33776451/

相关文章:

c++ - asio_handler_invoke 常量重载

python - 将 `functools.lru_cache` 应用于 lambda

c# - WPF - 在没有结构化异常处理的情况下检查资源是否存在

c++ - catch 站点异常的常见用法是什么?

java - 用于 Log4j 2 的 Log4jNestedDiagnosticContextFilter

java - JAXB:您是否必须指定要包含的每个字段?

java - 将 SAS 日期值转换为 Java YYYY-MM-DD

java - 相同的 appium 代码不适用于相同的应用程序

Python def 函数使用 lambda 赋值

asynchronous - 进行地面AsyncTask