What happens at OS level when a .net program exits due to an uncaught exception? What happens at OS level when a .net program exits due to an uncaught exception? windows windows

What happens at OS level when a .net program exits due to an uncaught exception?


Managed exceptions are implemented using the regular Windows Structured Exception Handling mechanisms. The exception code is 0xe0434f4d. Windows goes looking for an exception handler that's willing to handle the exception. If the code has no active try block on the stack, or no catch block is willing to catch the managed exception then the last gasp in managed code is the AppDomain.UnhandledException event.

If that isn't implemented either than exception handling switches to unmanaged handling, an exception filter set with SetUnhandledExceptionFilter gets a shot. Failing that, there is always a default handler provided by Windows. In normally invokes WER, the Windows Error Reporting program. That offers the user a dialog to send the exception details to Microsoft. Don't expect anything out of that.

By the time it has progressed beyond AppDomain.UnhandledException all info about the managed exception is lost. No stack trace, no exception message. Just the exception code, which you already know, and an exception address, which you'll have no use for because code is dynamically generated by the JIT compiler.

Be sure to trap the exception in the last gasp stage, write an event handler for AppDomain.UnhandledException. Log the value of e.ExcdeptionObject.ToString() and kill the program with Environment.Exit(). Also beware the Application.ThreadException event in Windows Forms code and Dispatcher.UnhandledException event in WPF code. They are a back stop for exceptions that are raised while processing events on the UI thread.


For native apps you can use the following functions:

Additionally you can use AddVectoredExceptionHandler although I wouldn't recommend this since it also intercepts the caught exceptions.

The function-pointer that you pass to SetUnhandledExceptionFilter gets a structure as input argument, containing all information about the exception (reason, registers, ...).

In my application I use SetUnhandledExceptionFilter to create an application dump (using the function MiniDumpWriteDump from the DBGHELP.DLL dll) if the application crashes.Be careful not doing too much in that function. Since your application already crashes, it's not guaranteed that any further logic will still work (e.g. accessing your own data structures which might be correct can cause further crashes).

Consider buying the book "Debugging Microsoft NET 2.0 Applications" by John Robbins. I learned a lot from this book, including this trick.