在lambda中处理lambda中没有try-catch的异常

Yod*_*oda 6 java lambda exception-handling java-8

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

我遇到以下代码,它的工作原理.为什么openStream()不要求处理IOException?我可以看到try-catch,tryWithResources但我不明白它背后的机制.

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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

Tun*_*aki 9

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

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) { }
Run Code Online (Sandbox Code Playgroud)

如果您尝试使用它,您将看到withCallable编译正常但withSupplier不编译; 即使lambda表达式与两个功能接口的签名兼容.

这背后的原因是Callable接口的功能方法call(),throws Exception在其签名中声明.Supplier.get()才不是.

引用JLS 第11.2.3节:

如果一个lambda体可以抛出一些异常类E,当E是一个经过检查的异常类而且E不是一个在lambda表达式所针对的函数类型的throws子句中声明的类的子类时,这是一个编译时错误.