当前位置:   article > 正文

java lambda无法使用,为什么不能在Java 8 lambda表达式中抛出异常?

为什么不能在java 8 lambda表达式中抛出异常?

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 entry : myMap.entrySet()) {

if(entry.getValue() == null) {

throw new MyException("Key '" + entry.getKey() + "' not found!");

}

}

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!");

}

});

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

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();

}

}

});

解决方案

You are not allowed to throw checked exceptions because the void accept(T t, U u) method in the BiConsumer 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 {

void accept(T t, U u); //

}

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()

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/294438
推荐阅读
相关标签
  

闽ICP备14008679号