小编Zho*_*hou的帖子

为什么在提供 lambda 参数时必须捕获异常?

考虑以下示例:

public class LambdaArgsTest {
    private static void display(Supplier<?> arg) {
        try {
            // this is the place where the Exception("wrong") might be thrown
            // and it is in fact handled
            System.out.println(arg.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        display(() -> {
            if(/*some condition*/) {
                // this statement will be rejected due to unhandled exception
                throw new Exception("wrong");
            }
            return "abcde";
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

问题来了:上面例子中的 lambda 参数是一个稍后将在“display()”方法中执行的对象。将参数传递给“display()”时显然不会执行它。

为什么会被编译器拒绝?我认为用 try...catch 包围它是很合理的,只有当 lambda 被实际调用时。

java lambda functional-interface

2
推荐指数
1
解决办法
65
查看次数

标签 统计

functional-interface ×1

java ×1

lambda ×1