【发布时间】:2021-09-11 06:18:54
【问题描述】:
我有一个用例,其中我需要从 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 块的路径存在资源泄漏。
现在,
- 我不能在 catch 中使用 printer.close(),因为我需要再次使用打印机,以便在 while 循环中进行下一次尝试。
- 我不能在我的代码中使用 finally{printer.close()},因为每次尝试都会执行它,我希望它在所有 try 语句之后关闭,即;所有的 while 循环迭代。
请告诉我该怎么做?
【问题讨论】:
-
尝试查找stackoverflow.com/questions/43441060/…。您实际上不需要使用
finally块。
标签: java error-handling while-loop logic try-catch-finally