The HandleProcessCorruptedStateExceptions: catching unmanaged exceptions in C#

When calling unmanaged code (for example C++) from within managed code, you want to be sure when accessing this unmanaged code from your managed code exceptions will be proper caught. When an access violation occurs within the unmanaged code (for example when trying to access a freed pointer), you want to catch this exception. These types of errors wil corrupt the process the unmanaged code is running in. A lot of people will put a catch (Exeption e) around it to be sure just all exceptions are caught from the (untrusted) external unmanaged code. To have a clear distingtion between corrupted process exceptions and all other exceptions, the development team of the .Net framework at Microsoft changed the CLR exception system so that all kinds of corrupted process exceptions will not be delivered anymore to your managed code.

There are however some ways to have the old CLR behavior (and retrieve the corrupted process exceptions within the CLR):
– Add an entry in your application configuration file:


An example configurationfile would look like this:

<?xml version="1.0" encoding="utf-8" ?>
 <legacyCorruptedStateExceptionsPolicy enabled="true" />

– Mark the method with the following attribute:


When using solution 1, your whole application will use the old mechanism. When using solution 2, only the method which is marked will be using the old mechanism.

There is a very good reason why you want to catch all process corrupted state exceptions: when using unmanaged libraries, you don’t want to crash your application due to a failure in the library. A very good in-depth description of the Unhandled Process Corrupted State exception can be found here:

Posted in C# by Bruno at September 10th, 2012.

3 Responses to “The HandleProcessCorruptedStateExceptions: catching unmanaged exceptions in C#”

  1. Seth says:

    But, if you use a library, the process it’s running in is the process of your application. Thus, is it safe to go on after having caught that kind of exception ?

    • Bruno says:

      Unmanaged code runs in another proces. When the library uses unmanaged code, you can use the mechanism described in my post. By caching the exception and take the apropiate action that deals with the error and continue. In this way you deal with the error.

  2. Trevor says:

    After years of fighting unmanaged exceptions with little more than printing output until I could find the problem lines… I discovered this. Thank you.

Leave a Reply