How to handle a System.AccessViolationException?

I use the external C library in my program encoded in C ++ / CLI with the .NET framework 4. Sometimes lib fails and I get the message:

Unhandled exception: System.AccessViolationException: attempt to read or write protected memory.

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

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

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

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

+4
source share
1 answer

For clarity, I copy / paste the answer provided in the Flot2011 comments here:

There are several ways around this:

  • Recompile as a .NET 3.5 assembly and run it in .NET 4.0.
  • Add a line to the application configuration file in the configuration / runtime item: <legacyCorruptedStateExceptionsPolicy enabled="true|false"/>
  • Decorate the methods you want to catch in these exceptions with the HandleProcessCorruptedStateExceptions attribute. See this article for more details.
+3
source

Source: https://habr.com/ru/post/1399013/


All Articles