Exception propagation in WinForms

Let’s start with the following code:

You throw exception as soon as your form is loaded, however, catch block is not executed. What happens?

Initially I though this is out of band exception which is thrown on another thread. But after some debugging the reason is much simpler. WinForms provide special event handler for unhandled exceptions, namely ThreadException. If you decompile some code, you can see this:

System.Windows.Forms.NativeWindow.Callback:

When you throw exception, it is being caught by WinForms and passed to the event handler. There we can see this:

System.Windows.Forms.Application.ThreadContext.OnThreadException:

The application is closed. Top level catch block is not executed because there is physically no exception anymore. Finally is being executed because of stack unwinding. If there was call to Environment.FailFast, it would not be executed.