Gracefully handling corrupted state exceptions
<p>Related to <a href="https://stackoverflow.com/q/39954552/1488067">this question</a>, 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 <code>catch (Exception ex)</code> at several places around the app?</p>

<p>So, after I specify the <code>&lt;legacyCorruptedStateExceptionsPolicy&gt;</code> attribute, if I understood correctly, all the <code>catch (Exception ex)</code> handlers will catch exceptions like <code>AccessViolationException</code> and happily continue.</p>

<p>Yeah, I know <code>catch (Exception ex)</code> 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 <a href="https://stackoverflow.com/a/29699442/1488067">unrelated exception</a> into the Event Log and then closes the process so that I cannot find out what actually happened.</p>

<p>The question is, how to make this happen, process wide:</p>

<pre><code>if the exception thrown is a Corrupted State Exception:
    - write the message to the log file
    - end the process 
</code></pre>

<p><strong>(Update)</strong></p>

<p>In other words, this would probably work for most exceptions in a simple app:</p>

<pre><code>[HandleProcessCorruptedStateExceptions] 
[SecurityCritical]
static void Main() // main entry point
{
    try 
    {

    }
    catch (Exception ex)
    {
        // this will catch CSEs
    }
}
</code></pre>

<p>But, it won't work for:</p>

<ul>
<li>Unhandled app domain exceptions (i.e. thrown on non-foreground threads)</li>
<li>Windows Service apps (which don't have an actual <code>Main</code> entry point)</li>
</ul>

<p>So it seems like <code>&lt;legacyCorruptedStateExceptionsPolicy&gt;</code> is the only way to make this work, in which case I don't know how to fail after logging the CSE?</p>