Why do we use finally blocks? [duplicate]
As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally
blocks at all?
Code A:
try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }
Code B:
try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code
Solution 1:
- What happens if an exception you're not handling gets thrown? (I hope you're not catching
Throwable
...) - What happens if you return from inside the try block?
- What happens if the catch block throws an exception?
A finally
block makes sure that however you exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.
Solution 2:
Note that (in Java at least, probably also in C#) it's also possible to have a try
block without a catch
, but with a finally
. When an exception happens in the try
block, the code in the finally
block is run before the exception is thrown higher up:
InputStream in = new FileInputStream("somefile.xyz");
try {
somethingThatMightThrowAnException();
}
finally {
// cleanup here
in.close();
}