Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed?
C# – Why use finally in C#
cexception handling
Related Topic
- C# – Direct casting vs ‘as’ operator
- C# – How to use reflection to call a generic method
- C# – Proper use of the IDisposable interface
- C# – What’s the @ in front of a string in C#
- C# – difference between “throw” and “throw ex”
- C# – Why catch and rethrow an exception in C#
- C# – Try-catch speeding up the code
- R – Make individual checkboxes on WPF datagrid not visible
Best Answer
The code inside a finally block will get executed regardless of whether or not there is an exception. This comes in very handy when it comes to certain housekeeping functions you need to always run like closing connections.
Now, I'm guessing your question is why you should do this:
When you can do this:
The answer is that a lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. With the latter code, the "alwaysDoThis();" call won't execute if the code inside the catch statement issues a return or throws a new exception.