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

Ralph Tandetzky picture Ralph Tandetzky · Jan 30, 2013 · Viewed 11.1k times · Source

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.

Answer

thang picture thang · Jan 30, 2013

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.