Search code examples
c#.neterror-handlingaccess-violationunmanaged

Handle Access Violation Exception that is not explicitly thrown by unmanaged code


I know Access Violation Exception is a serious problem that I should not really try to handle. I also know that in the latest version of .Net, one can handle this exception by

  1. put this <legacyCorruptedStateExceptionsPolicy enabled="true"> in the config and all the catch block would be able to catch the errors
  2. Decorate the methods you want to catch these exceptions in with the HandleProcessCorruptedStateExceptions attribute

Actually this made it very clear.

But my case is a little bit different and I cannot seem to find the solution: I am using an unmanaged c++ library which I will initialise it at some point of my application. Then this dll itself will perform some tasks by itself(pulling data from server to cache, logging etc.) This Access Violation Exception looks to be thrown during this process, not when the appication directly call the dll's api. So I have no way to try catch the offending logic.

At this stage I have managed to catch it in AppDomain.CurrentDomain.UnhandledException like so:

    [HandleProcessCorruptedStateExceptions, SecurityCritical]
    private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        Logger.Error("Unhandle Exception", (Exception)e.ExceptionObject);
    }

But I still cannot quite prevent the application from crashing. I know I probably should just let the application crash. But I really believe this error is not as bad as it appears and I just need to know how to suppress it, even though I might not use it.

Any thoughts?


Solution

  • Access violation exception are a sign of something going seriously wrong, and needs fixing. Continuing running after such errors is not advised since you cannot be sure about the state of your processes, and may cause more serious errors further down the line if you try to continue. If this is thrown on a thread started by the third party code there is little you can do to catch it as far as I know. I'm not sure why you think it is not as bad as it appears, but I would be very careful trying to deal with it.

    If it is in third party code that you do not have access to the best solution is probably to contact the author and have the issue fixed. The second best solution may be to run the third party code in a separate process. That way you can be sure that your process is not harmed if the code crashes.