是否有可能赶上访问冲突异常在.NET?有可能、冲突、异常、NET

2023-09-02 01:57:18 作者:一城烟雨柳色青

有什么我可以做,以捕获一个 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可能已经损坏进程的内存访问冲突已经提高了。这可以对任何部分电流过程的未predicted效果

You shouldn't. An access violation is a serious problem: it is an unexpected attempt to write to 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.

更多的细节:一个访问冲突是一个OS异常(所谓的SEH或者结构化异常处理的除外)。这是一个不同类型的异常不是从 System.Exception的的管理CLR例外。你很少会看到纯粹的管理code SEH异常,但如果发生,例如,在非托管code,CLR将其交付给管理code,你也能抓住它 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异常大多是不是一个好主意。进一步的细节将在文章中解释的的处理损坏的状态异常的 在MSDN杂志上,其中下面的文字就来自

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例外管理code。这不是一个问题,只要code不会尝试来处理异常情况,它不能合理地处理。访问冲突后,大多数程序不能安全地继续执行。不幸的是,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 这是真的,直到.NET 3.5。在.NET 4的行为已更改。如果您仍然希望能够赶上这类异常你就必须添加 legacyCorruptedStateExceptionsPolicy = TRUE 到的app.config。在articled进一步的细节上面链接。

1This was true until .NET 3.5. In .NET 4 the behavior has been changed. If you still want to be able to catch such kind of exceptions you would have to add legacyCorruptedState­­ExceptionsPolicy=true to the app.config. Further details in the articled linked above.