是否可以在.NET中捕获访问冲突异常? [英] Is it possible to catch an access violation exception in .NET?

查看:257
本文介绍了是否可以在.NET中捕获访问冲突异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么可以做的,以获取一个 AccessViolationException ?它被一个非托管的DLL抛出,我没有控制。

Is there anything I can do to catch an AccessViolationException? It is being thrown by a unmanaged DLL that I don't control.

推荐答案

你不应该。访问冲突是一个严重的问题:它是一个意外的尝试写入(或读取)一个无效的内存地址。正如约翰已经澄清的那样,非托管DLL可能已经在访问冲突提高之前损坏了进程内存。这可能对当前流程的任何部分产生不可预测的影响。

You shouldn't. An access violation is a serious problem: it is an unexpected attempt to write to (or read from) an invalid memory address. As John already clarified, the unmanaged DLL might already have corrupted the process memory before the access violation has been raised. This can have unpredicted effects on any part of the current process.

最安全的做法是通知用户然后立即退出。

The safest thing to do is to possibly inform the user and then immediately exit.

一些更多的细节:访问冲突是一个操作系统异常(所谓的SEH或结构化异常处理异常)。这是与 System.Exception 中的受管CLR异常不同的异常。您很少会在纯托管代码中看到SEH异常,但是如果发生这种情况,例如。在非托管代码中,CLR将提供给托管代码,您也可以抓住它 1

Some more details: An access violation is an OS exception (a so-called SEH or structured exception handling exception). This is a different kind of exception than the managed CLR exceptions from System.Exception. You will rarely see SEH exceptions in purely managed code, but if one occurs, e.g. in unmanaged code, the CLR will deliver it to managed code where you are also able to catch it1.

但是,捕获SEH异常是大多不是一个好主意。有关详细信息,请参见文章 处理损坏状态异常 ,其中以下文本取自:

However, catching SEH exceptions is mostly not a good idea. Further details are explained in the article Handling Corrupted State Exceptions in MSDN magazine where the following text it taken from:


CLR一直提供SEH异常使用与程序本身引发的异常相同的机制来管理代码。这不是一个问题,只要代码不尝试处理它不能合理处理的异常条件。大多数程序在访问冲突后无法安全地继续执行。不幸的是,CLR的异常处理模型一直鼓励用户通过允许程序捕获System.Exception层次结构顶部的任何异常来捕获这些严重的错误。但是这很少是正确的事情。

The CLR has always delivered SEH exceptions to managed code using the same mechanisms as exceptions raised by the program itself. This isn't a problem as long as code doesn't attempt to handle exceptional conditions that it cannot reasonably handle. Most programs cannot safely continue execution after an access violation. Unfortunately, the CLR's exception handling model has always encouraged users to catch these serious errors by allowing programs to catch any exception at the top of the System.Exception hierarchy. But this is rarely the right thing to do.

1 3.5。在.NET 4中,行为已被更改。如果你仍然希望能够捕获这样的异常,那么你必须向app.config添加 legacyCorruptedStateExceptionsPolicy = true

这篇关于是否可以在.NET中捕获访问冲突异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆