Java 8方法引用未处理的异常 [英] Java 8 method reference unhandled exception

查看:204
本文介绍了Java 8方法引用未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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);
}

此代码无法编译,错误不兼容的抛出类型*方法引用中的SomeException *

And this code doesn't compile, giving the error Incompatible thrown types *SomeException* in method reference.

IDEA也给了我错误未处理的异常

Also IDEA gave me the error unhandled exception.

所以,我的问题是为什么?为什么代码为每个循环编译并且不用lambda编译?

So, my question is why? Why code compiles with for each loop and doesn't compile with lambda?

推荐答案

如果你看一下 消费者< T> 接口,接受方法(这是您的方法引用实际使用的方法)未声明为抛出任何已检查的异常 - 因此您不能使用声明 的方法引用来抛出已检查的异常。增强的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆