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
You may want to put the code that you want to anyway get executed irrespective of what happens in your try or catch block.
Also if you are using multiple catch and if you want to put some code which is common for all the catch blocks this would be a place to put- but you cannot be sure that the entire code in try has been executed.
For example:
Finally always gets executed, where as your code after the catch may not.
finally
ALWAYS executes, unless the JVM was shut down,finally
just provides a method to put the cleanup code in one place.It would be too tedious if you had to put the clean up code in each of the
catch
blocks.There may be times when you want to execute a piece of code no matter what. Whether an exception is thrown or not. Then one uses
finally
.Throwable
...)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.Because you need that code to execute regardless of any exceptions that may be thrown. For example, you may need to clean up some unmanaged resource (the 'using' construct compiles to a try/finally block).