Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle System.AccessViolationException?

I'm using an external C library in my program coded in C++/CLI with the .NET framework 4. Sometimes the lib crashes and I get the message:

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory.

So I tried to handle it with a try/catch block:

try
{
  Init(); //< lib call which sometimes crashes
}
catch (Exception^ e)
{
  // handle the error
}

But the exception remains uncaught: my program crashes before entering the catch block.

How can I handle this exception to prevent my program from crashing?

like image 727
gregseth Avatar asked Oct 08 '22 13:10

gregseth


1 Answers

For clarity I copy/paste the answer given in the comments by Flot2011 here:

There are a few ways to get around this:

  • Recompile as a .NET 3.5 assembly and run it in .NET 4.0.
  • Add a line to your application's config file under the configuration/runtime element: <legacyCorruptedStateExceptionsPolicy enabled="true|false"/>
  • Decorate the methods you want to catch these exceptions in with the HandleProcessCorruptedStateExceptions attribute. See this article for details.
like image 152
gregseth Avatar answered Oct 12 '22 12:10

gregseth