c++seh

Get meaningful information from SEH exception via catch(...)?


Good Morning!

Edit: This is not a duplicate as it specifically pertains to SEH, not code-level thrown exceptions.

I'm using SEH to catch hardware errors thrown by some unreliable libraries. I'd like to get more information from the catchall exception. The following code simulates what I'm doing. As you can see, I'm using boost's current_exception_diagnostic_information, but it just spits out "No diagnostic information available." - not terribly helpful.

Is it possible to, at a minimum, get the termination code that would have been returned had the exception not have been caught? (In this case 0xC0000005, Access Violation)

#include "stdafx.h"
#include <future>
#include <iostream>
#include <boost/exception/diagnostic_information.hpp>

int slowTask()
{
    //simulates a dodgy bit of code
    int* a = new int[5]();
    a[9000009] = 3;
    std::cout << a[9000009];
    return 0;
}

int main()
{
    {
        try
        {
            std::future<int> result(std::async(slowTask));
            std::cout<< result.get();
        }
        catch(...)
        {
            std::cout << "Something has gone dreadfully wrong:"
                << boost::current_exception_diagnostic_information()
                << ":That's all I know."
                << std::endl;
        }           
    }

    return 0;
}

Solution

  • Using catch (...) you get no information at all, whether about C++ exceptions or SEH. So global handlers are not the solution.

    However, you can get SEH information through a C++ exception handler (catch), as long as you also use set_se_translator(). The type of the catch should match the C++ exception built and thrown inside your translator.

    The function that you write must be a native-compiled function (not compiled with /clr). It must take an unsigned integer and a pointer to a Win32 _EXCEPTION_POINTERS structure as arguments. The arguments are the return values of calls to the Win32 API GetExceptionCode and GetExceptionInformation functions, respectively.

    Or you can use __try/__except, which are specific to SEH. They can be used inside C++ just fine, including in programs where C++ exceptions are used, as long as you don't have SEH __try and C++ try in the same function (to trap both types of exceptions in the same block, use a helper function).