【发布时间】:2015-04-26 18:18:46
【问题描述】:
您能否解释一下为什么必须从 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.
}
});
}
现在似乎被调用者必须处理所有抛出的检查异常,而不是调用者。
【问题讨论】:
标签: java exception-handling lambda java-8 checked-exceptions