Search code examples
javaerror-handlingwhile-looplogictry-catch-finally

How to use finally block when using try-catch in a while loop


I have a usecase , wherein I need to read each line from a csv file : Each line has parameters for a function call. And I call the function for each entry.

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() >

Now my code got rejected because , there is a resource leak , i.e; printer is initialised before while loop , as I need it .. and the printer was closed after while loop . it covers just the path where try gets successfully executed, but when it doesn't cover the path where it throws an error , and as this path involving catch block has a resource leak.

Now ,

  1. I can't use printer.close() in catch , as I need the printer again for next try in the while loop.
  2. I can't use finally{printer.close()} in my code , as it gets executed for each try , and I want it just to close after all try statements i.e; all the while loop iterations.

Please let me know how do I do it?


Solution

  • If your printer implements java.lang.AutoCloseable. Just use try-with-resource