Java 8 方法引用未处理的异常 [英] Java 8 method reference unhandled exception
问题描述
我正在使用 Java 8 进行项目,发现了一种我无法理解的情况.
I'm working on project with Java 8 and found one situation which I can't understand.
我有这样的代码:
void deleteEntity(Node node) throws SomeException {
for (ChildNode child: node.getChildren()) {
deleteChild(child);
}
}
void deleteChild(Object child) throws SomeException {
//some code
}
这段代码运行良好,但我可以使用方法引用重写它:
This code is working fine, but I can rewrite it with a method reference:
void deleteEntity(Node node) throws SomeException {
node.getChildren().forEach(this::deleteChild);
}
并且这段代码无法编译,给出错误Incompatible throw types *SomeException* in method reference
.
And this code doesn't compile, giving the error Incompatible thrown types *SomeException* in method reference
.
IDEA 也给了我错误unhandled exception
.
Also IDEA gave me the error unhandled exception
.
所以,我的问题是为什么?为什么代码用 for 每个循环编译,而不用 lambda 编译?
So, my question is why? Why code compiles with for each loop and doesn't compile with lambda?
推荐答案
如果看Consumer
接口,accept
方法(这是您的方法引用将有效使用的方法)未声明为抛出任何已检查异常 - 因此您不能使用 被声明为 以抛出已检查异常的方法引用.增强的 for 循环没问题,因为您总是处于可以抛出 SomeException
的上下文中.
If you look at the Consumer<T>
interface, the accept
method (which is what your method reference would effectively be using) isn't declared to throw any checked exceptions - therefore you can't use a method reference which is declared to throw a checked exception. The enhanced for loop is okay, because there you're always in a context where SomeException
can be thrown.
您可能会创建一个包装器,将已检查的异常转换为未检查的异常,然后抛出该异常.或者,您可以使用 accept()
方法声明自己的函数式接口,该方法确实抛出一个检查异常(可能使用该异常参数化接口),然后编写自己的forEach
方法将该功能接口作为输入.
You could potentially create a wrapper which converts the checked exception to an unchecked exception, and throw that. Alternatively, you could declare your own functional interface with an accept()
method which does throw a checked exception (probably parameterizing the interface with that exception), and then write your own forEach
method that takes that functional interface as an input.
这篇关于Java 8 方法引用未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!