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

后端 未结 5 773
广开言路
广开言路 2020-12-01 10:38

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

5条回答
  •  天涯浪人
    2020-12-01 11:01

    you can wrap the call to the unmanaged DLL with a try-catch block. AccessViolationExceptions can be caught normally. Executing the following code shows both messages:

    try
    {
        throw new AccessViolationException();
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message + e.StackTrace, e.Message, MessageBoxButtons.OK, MessageBoxIcons.Error);
    }
    MessageBox.Show("Still running..");
    

    Edit: .NET 4 introduced a change in behavior, it is no longer possible to catch corrupted state exceptions unless you specifically "ask" the runtime to do so.

提交回复
热议问题