我有一个使用 BufferedWriter 写入数据(字符串)的块,但是编译器一直说错误:未报告的异常 IOException;必须被捕获或声明为抛出 this.dataContainer.stream().forEach( line -> writer.write(line) );
BufferWrite.write()
已经在try-catch块中了。它引发的错误是否嵌套在里面?if-else
应该怎么写?
void saveData() throws IOException {
String filename;
Path filePath;
BufferedWriter writer;
filename = "missionImpossible9.csv";
filePath = this.dirPath.resolve(filename); //make path of this file
writer = Files.newBufferedWriter(filePath);
try {
if (condition1) {
this.dataContainer1.stream().forEach( line -> writer.write(line) );
} else {
this.dataContainer2.stream().forEach( line -> writer.write(line) );
}
writer.close();
} catch (IOException err){
err.getStackTrace();}
}
问题是,
write()
的方法BufferedWriter
被声明为抛出IOException
,但是你在Consumer<?>
( )内部调用它.forEach()
,而()不应该抛出任何已检查的异常:表达式
line -> writer.write(line)
是实现功能接口的 lambda 表达式Consumer
,并且不能IOException
在 lambda 内部抛出已检查的异常(例如)。解决这个问题的方法是捕获
IOException
lambda 本身的内部,然后将其重新抛出并包装到RuntimeException
(未经检查的)中:此时您不需要
IOException
再捕捉(无论如何,如果IOException
发生 ,write()
您将收到它作为RuntimeException
有原因的IOException
。注意:有更好的方法可以保持类型
IOException
不变而不会引起编译器抱怨,这种方法称为 Sneaky Throw。您可能想阅读有关它的文章:Sneaky throws article。一般来说,不建议像这样静默已检查的异常,但有时别无选择(例如,当您想在 lambda 表达式中运行代码并且需要使用不会抛出异常的功能接口时,例如Consumer
)。