为什么不能在Java 8 lambda表达式中抛出异常? [英] Why can't I throw an exception in a Java 8 lambda expression?

查看:3553
本文介绍了为什么不能在Java 8 lambda表达式中抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我升级到Java 8,并试图用新的lamdba表达式通过Map替换简单的迭代。循环搜索空值,如果找到空值则抛出异常。旧的Java 7代码如下所示:

I upgraded to Java 8 and tried to replace a simple iteration through a Map with a new lamdba expression. The loop searches for null values and throws an exception if one is found. The old Java 7 code looks like this:

for (Map.Entry<String, String> entry : myMap.entrySet()) {
    if(entry.getValue() == null) {
        throw new MyException("Key '" + entry.getKey() + "' not found!");
    }
}

我尝试将其转换为Java 8看起来像这样:

And my attempt to convert this to Java 8 looks like this:

myMap.forEach((k,v) -> {
    if(v == null) {
        // OK
        System.out.println("Key '" + k+ "' not found!");

        // NOK! Unhandled exception type!
        throw new MyException("Key '" + k + "' not found!");
    }
});

任何人都可以解释为什么 throw 允许这里,这可以如何纠正?

Can anyone explain why the throw statement not allowed here and how this could be corrected?

Eclipse的快速修复建议对我来说不正确,它只是围绕 throw 语句与 try-catch 块:

Eclipse's quick-fix suggestion does not look right to me... it simply surrounds the throw statement with a try-catch block:

myMap.forEach((k,v) -> {
    if(v == null) {
        try {
            throw new MyException("Key '" + k + "' not found!");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
});


推荐答案

您不能抛出检出的异常,因为 void accept(T t,U u)方法在 BiConsumer< T,U> 接口中不会抛出任何异常。而且,如你所知, forEach 需要这样的类型。

You are not allowed to throw checked exceptions because the void accept(T t, U u) method in the BiConsumer<T, U> interface doesn't throw any exceptions. And, as you know, forEach takes such type.

public void forEach(BiConsumer<? super K, ? super V> action) { ... }
                         |
                         V
@FunctionalInterface
public interface BiConsumer<T, U> {
    void accept(T t, U u); // <-- does throw nothing
}

当我们说话时关于检查的例外。但是您可以抛出一个未经检查的异常,例如,一个 IllegalArgumentException

That's true when we're talking about checked exceptions. But you are allowed to throw an unchecked exception, for instance, an IllegalArgumentException:

new HashMap<String, String>()
    .forEach((a, b) -> { throw new IllegalArgumentException(); });

这篇关于为什么不能在Java 8 lambda表达式中抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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