0

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?

Deshan Koswatte
  • 138
  • 1
  • 12
  • try looking up https://stackoverflow.com/questions/43441060/java-try-without-catch-and-catch-without-try. You actually do not need to use `finally` block. – dodobird Jun 29 '21 at 03:11

2 Answers2

0

Maybe you can move your while statement inside the try-catch-finally block. And call printer.close() in the finally block.

Sai H.
  • 66
  • 5
0

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

Cwift
  • 300
  • 1
  • 6