How can I handle an access violation in Visual Studio C++?

蓝咒 提交于 2019-12-30 07:27:28

问题


Usually an access violation terminates the program and I cannot catch a Win32 exception using try and catch. Is there a way I can keep my program running, even in case of an access violation? Preferably I would like to handle the exception and show to the user an access violation occurred.

EDIT: I want my program to be really robust, even against programming errors. The thing I really want to avoid is a program termination even at the cost of some corrupted state.


回答1:


In Windows, this is called Structured Exception Handling (SEH). For details, see here:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms680657%28v=vs.85%29.aspx

In effect, you can register to get a callback when an exception happens. You can't do this to every exception for obvious reasons.

Using SEH, you can detect a lot of exceptions, access violations included, but not all (e.g. double stack fault). Even with the exceptions that are detectable, there is no way to ensure 100% stability after the exception. However, it may be enough to inform the user, log the error, send a message back to the server, and gracefully exit.




回答2:


I will start by saying that your question contains a contradiction:

EDIT: I want my program to be really robust, ... The thing I really want to avoid is a program termination even at the cost of some corrupted state.

A program that keeps on limpin' in case of corrupted state isn't robust, it's a liability.


Second, an opinion of sorts. Regarding:

EDIT: I want my program to be really robust, even against programming errors. ...

When, by programming errors you mean all bugs, then this is impossible.

If by programming errors you mean: "programmer misused some API and I want error messages instead of a crash, then write all code with double checks built in: For example, always check all pointers for NULL before usage, even if "they cannot be NULL if the programmer didn't make a mistake", etc. (Oh, you might also consider not using C++ ;-)

But IMHO, some amount of program-crashing-no-matter-what bugs will have to be accepted in any C++ application. (Unless it's trivial or you test the hell out of it for military or medical use (even then ...).)


Others already mentioned SEH -- it's a "simple" matter of __try / __catch.

Maybe instead of trying to catch bugs inside the program, you could try to become friends with Windows Error Reporting (WER) -- I never pulled this, but as far as I understand, you can completely customize it via the OutOfProcessException... callback functions.



来源:https://stackoverflow.com/questions/14610879/how-can-i-handle-an-access-violation-in-visual-studio-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!