考虑以下示例:
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 被实际调用时。