The finally block (nearly) always executes, whether or not there was an exception.
I say nearly because there are a few cases where finally isn’t guaranteed to be called:
- If there is an infinite loop or deadlock in your code so that the execution remains inside the try or catch blocks then the finally block will never execute.
- If your application is terminated abruptly by killing the process.
- Power cut.
- Calling Environment.FailFast.
- Some exceptions such as:
- StackOverflowException
- OutOfMemoryException
- ExecutingEngineException (now obsolete)
- An exception thrown in a finalizer (source).
Furthermore, even if the finally block is entered if a ThreadAbortException
occurs just as the thread enters the finally block the code in the finally block will not be run.
There may be some other cases too…