【发布时间】:2020-10-09 14:51:32
【问题描述】:
考虑以下示例:
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";
});
}
}
问题来了:上例中的 lambda 参数是稍后将在“display()”方法中执行的对象。将参数传递给“display()”时显然不会执行。
为什么会被编译器拒绝?我认为只在实际调用 lambda 时用 try...catch 包围它是很合理的。
【问题讨论】:
-
因为检查的异常需要声明或捕获,而您两者都不做。何时抛出它们并不重要。
-
如果您将
Supplier更改为Callable,这确实会引发期望,它会编译得很好。 -
添加
ThrowingSupplier的情况并不少见,例如我为此编写的那个。 javadoc.io/doc/net.openhft/chronicle-core/latest/net/openhft/…
标签: java lambda functional-interface