A c access violation error gets thrown at some part of my code. I would like to "catch" it and log the faulting line so I can investigate further. I tried the first answer in this thread: Catching access violation exceptions?
Unfortunately no luck so far. I am using debug mode in Visual Studio 2019. Anyone knows a way how to log the faulting line?
CodePudding user response:
The "Access Violation", that you are referring to, cannot happen in well-formed code. It is always the result of undefined behavior.
When that happens the state of your program is unknown, and is corrupted in some unspecified and unknown way. You cannot expect to accomplish any meaningful task in the program, any more, because the state of the program is no longer known. I suppose that if the operating system protects the program's code segment read-only you could rely on the fact that the actual code is intact, but the stack is in unknown state, and you can forget all about the heap, its state is completely unknown.
The only meaningful means to extract any useful diagnostics from the flawed program is by using an external debugger to analyze and inspect the frozen snapshot of the program's state at that point, from an external view.
CodePudding user response:
On Windows, you can do it with __try
... __except
, as in the following simplified example:
__try
{
* (int *) 0 = 0;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
std::cout << "Exception caught\n";
}
Microsoft call this mechanism 'structured exception handling' and it is much more powerful (and, indeed, usable) than signals on Unix and I encourage you to learn more about it if you want to do this kind of thing:
https://docs.microsoft.com/en-us/cpp/cpp/try-except-statement?view=msvc-170
I use it to catch exceptions in poorly behaved ASIO drivers which would otherwise crash my app.