【问题标题】:How to use finally block when using try-catch in a while loop在while循环中使用try-catch时如何使用finally块
【发布时间】: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 块的路径存在资源泄漏。

现在,

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

请告诉我该怎么做?

【问题讨论】:

标签: java error-handling while-loop logic try-catch-finally


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      相关资源
      最近更新 更多