【发布时间】:2022-02-10 21:54:40
【问题描述】:
在下面的代码中,我在方法签名中编写了 throws,但在 Lambda 中再次为 write 编写,编译器给出了错误。为什么?
编译器错误:未处理的异常:java.io.IOException
public void saveTodoItems() throws IOException {
try (BufferedWriter outputStream = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("TodoItems.txt"), StandardCharsets.UTF_8))) {
todoItems.forEach(todoItem -> {
outputStream.write(todoItem.getShortDescription() + "\t" //compile error on write
+ todoItem.getDetail() + "\t"
+ todoItem.getDeadLine()+"\n");
});
}
}
【问题讨论】:
-
什么是
todoItems?某种清单?还有什么错误? -
@byxor 是的,它是一个数组列表,编译器错误是:未处理的异常:java.io.IOException
-
IOException是“检查异常”。无论您使用 lambda 实现了什么接口,它都不会声明该方法将引发 IOException。您可能需要在 lambda 中使用 try/catch -
@byxor "Whatever interface you've implemented" 它是 Iterable 的 forEach,所以它只是 java.util.function.Consumer。
-
这里只使用常规的for循环。