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

不想你离开。 提交于 2019-12-01 01:30:21

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.

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.

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