在while循环中使用try-catch时,如何使用finally块



我有一个用例,其中我需要从csv文件中读取每一行:每一行都有一个函数调用的参数。我为每个条目调用函数。

while(csvReader.readLine != null){
try {
the line is divided into two parameters based on , delimiter;
call function(line as parameter);
filePrinter.print(successfulParameter.csv);
} catch (Exception from function()) {
log the exception;                  
anotherFilePrinter.print(unsuccesfulParameter&Exception.csv);
}
}
I closed all reader, printer...< printer.close() >

现在我的代码被拒绝了,因为存在资源泄漏,即;打印机在while循环之前已初始化,因为我需要它。。并且打印机在while循环之后关闭。它只覆盖try成功执行的路径,但当它不覆盖抛出错误的路径时,由于这个涉及catch块的路径存在资源泄漏。

现在,

  1. 我无法在catch中使用printer.close((,因为我需要在while循环中再次使用打印机
  2. 我不能在我的代码中使用finally{printer.close((},因为它每次尝试都会被执行,我希望它只在所有尝试语句之后关闭,即;一直循环迭代

请告诉我该怎么做?

如果您的printer实现了java.lang.AutoCloseable。只需使用try with resource

也许您可以将while语句移动到try-catch finally块中。并在finally块中调用printer.close()

最新更新