Basically I’ve heard that certain conditions will cause .NET to blow past the finally block. Does anyone know what those conditions are?
Basically I’ve heard that certain conditions will cause .NET to blow past the finally block. Does anyone know what those conditions are?
Two possibilities:
The finally block will not be executed when there's a StackOverflowException since there's no room on the stack to even execute any more code. It will also not be called when there's an ExecutionEngineException, which may arise from a call to Environment.FailFast().
Unless the CLR blows up and goes down with an ExecutingEngineException (I've seen a few in the .net 1.1 days with just the right amount of COM Interop :) .. I think finally should always execute.
You can get a situation where the code in the try block causes a SecurityException to be thrown before the try block entered (instead the exception is thrown when the containing method is called (see http://msdn.microsoft.com/en-us/library/fk6t46tz(VS.71).aspx)), in this situation you never even enter the try block so the code in the finally block is never called.
Other possibilities include StackOverflowException, and ExecutingEngineException.
Since async/await, there is another way a finally might get ignored that I haven't seen mentioned in other answers:
static class Program
{
[STAThread]
static void Main()
{
async void ThreadExecutionAsync()
{
try
{
SynchronizationContext.SetSynchronizationContext(
new WindowsFormsSynchronizationContext());
await Task.Yield(); // Yield to the context
// The WindowsFormsSynchronizationContext will schedule the continuation
// on the main thread, so the current thread will die
// and we will never get here...
Debugger.Break();
}
finally
{
// Will never get here either...
Debugger.Break();
}
}
var thread = new Thread(ThreadExecutionAsync);
thread.Start();
Application.Run();
}
}