Monday, February 27, 2012

"Try-Catch Not Catching Exceptions": Corrupted State Exceptions

I had an issue of some of our document conversion applications crashing due to exceptions thrown from unmanaged code in third party libraries (eg.AbcPDF,…,etc). I often got the “Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt” exception. These exceptions cannot be caught from try/catch blocks and leads the whole application to crash.

I found that this can be solved using either of the following methods in.Net 4.0:

1.       Add the HandleProcessCorruptedStateExceptionsAttribute to the methods with the try/catch blocks. or
2.       Add the following lines to the config file:
<configuration>
    <runtime>
        <legacyCorruptedStateExceptionsPolicy enabled="true"/>
    </runtime>
</configuration>

When either of the above is implemented, the CLR will deliver those exceptions to try/catch and I was able to  gracefully take necessary actions.

For further details, please visit: