2 回答

TA贡献1847条经验 获得超11个赞
因为 lambda 表达式并不总是立即计算。
让你有这个:
public Supplier<String> giveMeASupplier() throws Exception {
return () -> someMethodThatThrowsCheckedException()
}
根据您的说法,上述方法可行。对?
现在在另一种方法中,我可以这样做:
Suppler<String> supplier = null;
try {
supplier = giveMeASupplier() // no exception is thrown here.
} catch (Exception ex) {
ex.printStackTrace();
}
if (supplier != null) {
System.out.println(supplier.get()); // this might throw an exception! Yet it's not in a try...catch!
}
现在你认为如果supplier.get()抛出异常会发生什么?有什么可以抓住的吗?不,如果以某种方式catch运行前几行的块,那将非常奇怪。

TA贡献1846条经验 获得超7个赞
简单的答案是您所指的“方法”是Consumer.accept
,而不是 YourClass.testing
。
lambdas -> queue.offerLast(s, 10000, TimeUnit.MILLISECONDS)
是 的一个实现java.util.function.Consumer.accept(T)
,它没有声明它可以 throw InterruptedException
。
而且这种行为并非特定于流,无论在何处定义 lambda 表达式,它都必须符合其实现的功能接口的抽象方法的签名。
添加回答
举报