Is it possible to catch an access violation exception in .NET?

Viewed 23769

Is there anything I can do to catch an AccessViolationException? It is being thrown by a unmanaged DLL that I don't control.

5 Answers

As others pointed out, you shouldn't "handle" this condition, but during development it is handy to catch this for the sake of troubleshooting.

You can mark your managed method with the System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions attribute:

[HandleProcessCorruptedStateExceptions]
public void MyMethod()
{
    try
    {
        NaughtyCall();
    }
    catch (AccessViolationException e)
    {
        // You should really terminate your application here
    }
}
Related