C#中的System.AccessViolationException异常捕捉

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

官方解释

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

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

解决方案

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

1
2
3
4
5
<configuration>
   <runtime>
      <legacyCorruptedStateExceptionsPolicy enabled="true" />
   </runtime>
</configuration>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[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 @   我也是个傻瓜  阅读(2365)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示