为什么不能在方法级别抛出 Java 流中的已检查异常?

我一直在学习并发和流,API并遇到了这个。该offerLast()方法可以 throw 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));

}

我知道它可以通过将它包围在 a 中来解决try/catch,或者通过创建wrapper method处理 的a来解决error,但我仍然试图理解为什么它不能在方法级别抛出。


MMMHUHU
浏览 141回答 2
2回答

回首忆惘然

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

喵喵时光机

简单的答案是您所指的“方法”是Consumer.accept,而不是&nbsp;YourClass.testing。lambdas -> queue.offerLast(s, 10000, TimeUnit.MILLISECONDS)是 的一个实现java.util.function.Consumer.accept(T),它没有声明它可以 throw&nbsp;InterruptedException。而且这种行为并非特定于流,无论在何处定义 lambda 表达式,它都必须符合其实现的功能接口的抽象方法的签名。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java