Search code examples
javaexceptiontry-catch-finally

Is finally block really necessary for the clean up code (like closing streams)?


I am very confused as to why do I need to need to put the clean-up code like closing streams in a finally block.

I've read that the code in finally block will run no matter what (whether there's an exception); and after the finally block runs, the rest of the method continues.

My question is: if the rest of the method has to continue then why don't I put the clean-up code after my try/catch block in a function?


Solution

  • The finally block will always run if an uncaught exception is thrown, but the rest of the code in the method will be skipped.

    So if you put clean-up code after the finally block, it won't get called if there is an exception.