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
But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return , continue , or break . Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
In C#, multiple finally blocks in the same program are not allowed. The finally block does not contain any return, continue, break statements because it does not allow controls to leave the finally block.
In this meaning, finally most commonly occurs in the normal mid position for adverbs, between the subject and the main verb, after the modal verb or the first auxiliary verb, or after be as a main verb: There were no taxis and we finally got home at 2 pm.
Explanation: Sometimes there is a need to execute a set of code every time the program runs. Even if the exception occurs and even if it doesn't, there can be some code that must be executed at end of the program. That code is written in finally block. This block is always executed regardless of exceptions occurring.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With