C#中的System.AccessViolationException异常捕捉

我们经常使用try-catch来捕捉异常,但从.NET 4.0开始异常处理机制有所改变,导致AccessViolationException这类异常无法通过try-catch捕捉,而导致程序崩溃。

官方解释

AccessViolationException当代码尝试读取或写入尚未分配或无权访问的内存时,非托管或不安全代码中会发生访问冲突。这种异常一般都是严重错误。

从.NET Framework 4 开始,AccessViolationException如果异常发生在公共语言运行时保留的内存之外,则结构化异常处理程序中的 语句不会处理catch公共语言运行时引发的异常。 若要处理此类 AccessViolationException 异常,请将 HandleProcessCorruptedStateExceptionsAttribute 属性应用于引发异常的方法。

解决方案

方案一:不修改代码,通过config配置来统一设置为.NET 3.5异常处理机制。

<configuration>
   <runtime>
      <legacyCorruptedStateExceptionsPolicy enabled="true" />
   </runtime>
</configuration>

方案二、修改代码,增加特性,针对某个函数有效。

[HandleProcessCorruptedStateExceptions] 
[SecurityCritical]
public static int Main() 
{ 
   try
     {
       // Catch any exceptions leaking out of the program CallMainProgramLoop(); 
     }
   catch (Exception e) 
     {
         // The exception we caught could have been a program error
        // or something much more serious. Regardless, we know that
        // something is not right. We'll just output the exception 
       // and exit with an error. We won't try to do any work when
       // the program or process is in an unknown state!

        System.Console.WriteLine(e.Message); 
        return 1; 
     } 
  return 0; 
}
posted @ 2023-08-02 14:36  我也是个傻瓜  阅读(1545)  评论(0编辑  收藏  举报