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:

legacyCorruptedState­­ExceptionsPolicy=true

An example configurationfile would look like this:

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

– Mark the method with the following attribute:

[HandleProcessCorruptedStateExceptions]

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: http://msdn.microsoft.com/en-us/magazine/dd419661.aspx

Posted in C# at September 10th, 2012. 3 Comments.