Instead of using <legacyCorruptedStateExceptionsPolicy> it would be better to use [HandleProcessCorruptedStateExceptions] (and [SecurityCritical] ), as indicated here:
https://msdn.microsoft.com/en-us/magazine/dd419661.aspx
After that, your Main method should look something like this:
[HandleProcessCorruptedStateExceptions, SecurityCritical] static void Main(string[] args) { try { ... } catch (Exception ex) {
But keep in mind that this does not catch more serious exceptions such as StackOverflowException and ExecutionEngineException .
Also, finally involved try blocks will not execute:
https://csharp.2000things.com/2013/08/30/920-a-finally-block-is-not-executed-when-a-corrupted-state-exception-occurs/
For other unhandled appdomain exceptions, you can use:
AppDomain.CurrentDomain.UnhandledExceptionApplication.Current.DispatcherUnhandledExceptionTaskScheduler.UnobservedTaskException
(Please search for details when a particular handler is appropriate for your situation. For example, TaskScheduler.UnobservedTaskException little more complicated.)
If you don’t have access to the Main method, you can also tag the AppDomain exception handler to catch the CSE:
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; ... [HandleProcessCorruptedStateExceptions, SecurityCritical] private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
The last line of defense may be an unmanaged UnhandledExceptionFilter as follows:
[DllImport("kernel32"), SuppressUnmanagedCodeSecurity] private static extern int SetUnhandledExceptionFilter(Callback cb);
And then somewhere at the beginning of your process:
SetUnhandledExceptionFilter(ptrToExceptionInfo => { var errorCode = "0x" + Marshal.GetExceptionCode().ToString("x2"); ... return 1; });
More information on possible return codes can be found here:
https://msdn.microsoft.com/en-us/library/ms680634(VS.85).aspx
The “specialty” of UnhandledExceptionFilter is that it is not called if a debugger is connected. (At least not in my case with a WPF application.) Be aware of this.
If you set all the relevant ExceptionHandlers on top, you must log all exceptions that may be logged. For more serious exceptions (like StackOverflowException and ExecutionEngineException ) you should find a different path because the whole process is not possible after they have occurred. A possible way could be another process that monitors the main process and logs any fatal errors.
Additional hints: