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?

1

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.