如何对嵌套在if-else中的BufferedWriter.write使用try-catch(IOException)?

问题描述 投票:0回答:1

我有一个使用 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();}
}
java exception try-catch ioexception bufferedwriter
1个回答
0
投票

问题在于

write()
的方法
BufferedWriter
被声明为抛出
IOException
,但是您在
Consumer<?>
.forEach()
)内调用它,而该方法不应该抛出任何已检查的异常:

this.dataContainer1.stream().forEach( line -> writer.write(line) );

表达式

line -> writer.write(line)
是实现函数式接口
Consumer
的 lambda 表达式,并且您不能在 lambda 内抛出已检查异常(例如
IOException
)。

解决这个问题的方法是捕获 lambda 本身内部的

IOException
,并将其重新包装成
RuntimeException
(未选中):

this.dataContainer1.stream().forEach(line -> {
        try {
            writer.write(line);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

此时,您不再需要捕获

IOException
(无论如何,如果
IOException
发生于
write()
,您将收到它作为导致
RuntimeException
IOException

© www.soinside.com 2019 - 2024. All rights reserved.