我一直在学习并发性和流,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
或通过创建wrapper method
处理的来解决error
,但我仍在尝试理解为什么不能在方法级别将其抛出。
因为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
运行几行之前将其阻塞,那么它将真的很奇怪。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句