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
If catch block throws any exception then remaining code will not executed hence we have to write finaly block.
Even though our application is closed forcefully there will be some tasks, which we must execute (like memory release, closing database, release lock, etc), if you write these lines of code in the
finally
block it will execute whether an exception is thrown or not...Your application may be a collection of threads,
Exception
terminates the thread but not the whole application, in this casefinally
is more useful.In some cases
finally
won't execute such as JVM Fail, Thread terminate, etc.Note that (in Java at least, probably also in C#) it's also possible to have a
try
block without acatch
, but with afinally
. When an exception happens in thetry
block, the code in thefinally
block is run before the exception is thrown higher up: