检查从lambda表达式中抛出的异常 [英] Checked exceptions thrown from within lambda expressions
问题描述
public void doSomething(ObjectInputStream istream)throws IOException {
//读取方法抛出IOException。
IntStream.range(0,10).forEach(i - > someList.add(read(istream)));
}
但这一个?
public void doSomething(ObjectInputStream istream)throws IOException {
IntStream.range(0,10).forEach(i - > {
try {
//读取方法抛出一个IOException
someList.add(read(istream));
}
catch(IOException ioe){
// Callee has to处理检查的异常,而不是调用者。
}
});
}
似乎被调用方现在必须处理抛出的任何检查的异常,不是调用者。
问题不是lambda表达式,它是它实现的接口。记住,lambda表达式基本上只是实现给定界面的匿名类的简写。
在这种情况下, forEach
需要一个 java.util.function.Consumer< T>
:
public interface Consumer< T> {
void accept(T t);
...
}
请注意, accept
未声明扔任何东西。这意味着没有执行它可以抛出任何东西;不是一个命名的类,而不是匿名类,而不是一个lambda。
Can you please explain why checked exceptions have to be caught from within lambda expressions? In other words, why does the following code not compile...
public void doSomething(ObjectInputStream istream) throws IOException {
// The read method throws an IOException.
IntStream.range(0, 10).forEach(i -> someList.add(read(istream)));
}
but this one will?
public void doSomething(ObjectInputStream istream) throws IOException {
IntStream.range(0, 10).forEach(i -> {
try {
// The read method throws an IOException.
someList.add(read(istream));
}
catch (IOException ioe) {
// Callee has to handle checked exception, not caller.
}
});
}
It seems like the callee now has to handle any checked exceptions that are thrown and not the caller.
The issue isn't the lambda expression, it's the interface it's implementing. Remember, a lambda expression is basically just shorthand for an anonymous class that implements a given interface.
In this case, forEach
takes a java.util.function.Consumer<T>
:
public interface Consumer<T> {
void accept(T t);
...
}
Note that accept
is not declared to throw anything. This means that no implementation of it can throw anything; not a named class, not an anonymous class, and not a lambda.
这篇关于检查从lambda表达式中抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!