您能否解释一下为什么必须从 lambda 表达式中捕获已检查的异常?换句话说,为什么下面的代码不能编译...
public void doSomething(ObjectInputStream istream) throws IOException {
// The read method throws an 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 {
// The read method throws an IOException.
someList.add(read(istream));
}
catch (IOException ioe) {
// Callee has to handle checked exception, not caller.
}
});
}
似乎被调用者现在必须处理抛出的所有已检查异常,而不是调用者。
最佳答案
问题不在于 lambda 表达式,而在于它所实现的接口(interface)。请记住,lambda 表达式基本上只是实现给定接口(interface)的匿名类的简写。
在这种情况下,forEach
需要 java.util.function.Consumer<T>
:
public interface Consumer<T> {
void accept(T t);
...
}
请注意 accept
没有声明要扔任何东西。这意味着它的任何实现都不能抛出任何东西;不是命名类,不是匿名类,也不是 lambda。
关于java - 从 lambda 表达式中抛出的已检查异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28707435/