![](/img/trans.png)
[英]Why NullPointerException is not thrown in the following Java Stream filter method
[英]Why can't checked exceptions in a java stream be thrown at method level?
我一直在学习有关并发性和流API
。 offerLast()
方法可以引发InterruptedException
,因此我必须处理它。 我不明白的是为什么我不能通过添加throws Exception
将它扔到方法级别? 因为它是此code
无法编译。
static BlockingDeque<Integer> queue = new LinkedBlockingDeque<>();
public static void testing() throws Exception {
IntStream.iterate(1, i -> i+1).limit(5)
.parallel()
.forEach(s -> queue.offerLast(s, 10000, TimeUnit.MILLISECONDS));
}
我知道可以通过将其包围在try/catch
,或者通过创建处理error
的wrapper method
来解决它,但是我仍在尝试理解为什么不能在方法级别将其抛出。
因为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
在运行前以某种方式阻塞了几行,那将是很奇怪的。
简单的答案是,您所指的“方法”是Consumer.accept
,而不是YourClass.testing
。
lambda s -> queue.offerLast(s, 10000, TimeUnit.MILLISECONDS)
是java.util.function.Consumer.accept(T)
,该声明没有声明可以抛出InterruptedException
。
而且,这种行为并不特定于流,无论在哪里定义了lambda表达式,它都必须遵守其实现的功能接口的抽象方法的签名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.