Search code examples
c++windowsvisual-studioexceptionaccess-violation

Catch c++ Access Violation exception


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?


Solution

  • 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://learn.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.