Related to this question, I would like to force CLR to let my .NET 4.5.2 app catch Corrupted State Exceptions, for the sole purpose of logging them and then terminating the application. What's the correct way to do this, if I have catch (Exception ex)
at several places around the app?
So, after I specify the <legacyCorruptedStateExceptionsPolicy>
attribute, if I understood correctly, all the catch (Exception ex)
handlers will catch exceptions like AccessViolationException
and happily continue.
Yeah, I know catch (Exception ex)
is a Bad Idea™, but if CLR would at least put the correct stack trace into the Event Log, I would be more than happy to explain to the customer that his server app failing fast at 1AM and being offline for the night is a good thing. But unfortunately, CLR logs an unrelated exception into the Event Log and then closes the process so that I cannot find out what actually happened.
The question is, how to make this happen, process wide:
if the exception thrown is a Corrupted State Exception:
- write the message to the log file
- end the process
(Update)
In other words, this would probably work for most exceptions in a simple app:
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
static void Main() // main entry point
{
try
{
}
catch (Exception ex)
{
// this will catch CSEs
}
}
But, it won't work for:
- Unhandled app domain exceptions (i.e. thrown on non-foreground threads)
- Windows Service apps (which don't have an actual
Main
entry point)
So it seems like <legacyCorruptedStateExceptionsPolicy>
is the only way to make this work, in which case I don't know how to fail after logging the CSE?
Instead of using
<legacyCorruptedStateExceptionsPolicy>
it would be better to use[HandleProcessCorruptedStateExceptions]
(and[SecurityCritical]
) as stated here:https://msdn.microsoft.com/en-us/magazine/dd419661.aspx
Following that, your
Main
method should look something like this:But be aware that this doesn't catch the more serious exceptions like
StackOverflowException
andExecutionEngineException
.Also
finally
of involvedtry
blocks will not be executed: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.UnhandledException
Application.Current.DispatcherUnhandledException
TaskScheduler.UnobservedTaskException
(Please do a search for the details when a specific handler is appropriate for your situation.
TaskScheduler.UnobservedTaskException
for example is a bit tricky.)If you don't have access to the
Main
method, you can also mark your AppDomain exception handler to catch the CSE:The last line of defense could be an unmanaged UnhandledExceptionFilter like this:
And then somewhere at the beginning of your process:
You can find more information about the possible return codes here:
https://msdn.microsoft.com/en-us/library/ms680634(VS.85).aspx
A "specialty" of the
UnhandledExceptionFilter
is that it isn't called if a debugger is attached. (At least not in my case of having a WPF app.) So be aware of that.If you set all the appropriate ExceptionHandlers from above, you should be logging all exceptions that can be logged. For the more serious exceptions (like
StackOverflowException
andExecutionEngineException
) you have to find another way because the whole process is unusable after they happened. A possible way could perhaps be another process that watches the main process and logs any fatal errors.Additional hints:
AppDomain.CurrentDomain.UnhandledException
you can safely cast thee.ExceptionObject
toException
without having to worry - at least if you don't have any IL code that throws other objects thanException
: Why is UnhandledExceptionEventArgs.ExceptionObject an object and not an Exception?Dispatcher.UnhandledException
for the other dispatchers.Thanks to @haindl for pointing out that you can also decorate handler methods with the
[HandleProcessCorruptedStateExceptions]
1 attribute, so I made a little test app just to confirm if things really work as they are supposed to.1 Note: Most answers state that I should also include the
[SecurityCritical]
attribute, although in the tests below omitting it didn't change the behavior (the[HandleProcessCorruptedStateExceptions]
alone seemed to work just fine). However, I will leave both attributes below since I am presuming all these folks knew what they were saying. That's a school example of "Copied from StackOverflow" pattern in action.The idea is, obviously, to remove the
<legacyCorruptedStateExceptionsPolicy>
setting fromapp.config
, i.e. only allow our outermost (entry-level) handler(s) to catch the exception, log it, and then fail. Adding the setting will allow your app to continue, if you catch the exception in some inner handler, and this is not what you want: the idea is just to get the accurate exception info and then die miserably.I used the following method to throw the exception:
1. Catching exceptions from
Main
:2. Catching all exceptions, including background threads/tasks:
I would recommend using just the latter approach, and removing the
[HandleProcessCorruptedStateExceptions]
from all other places to make sure the exception doesn't get caught at the wrong place. I.e. if you have atry/catch
block somewhere and anAccessViolationException
is thrown, you want CLR to skip thecatch
block and propagate to theUnhandledException
before ending the app.