如何将 std::set_terminate 与 SetUnhandledExceptionFilter 一起使用?

And*_*zos 1 c++ windows winapi c++17

有什么方法可以获取.what()未捕获的 C++ 异常,同时还安装了 Windows 未处理的异常过滤器?

为了演示,以下程序...

#include <windows.h>
#include <iostream>

static LONG WINAPI WindowsExceptionHandler(LPEXCEPTION_POINTERS ep) {
    std::cerr << "FOO" << std::endl;
    return EXCEPTION_EXECUTE_HANDLER;
}

void TerminateHandler() {
    std::exception_ptr exception_ptr = std::current_exception();
    try {
        if (exception_ptr) std::rethrow_exception(exception_ptr);
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
}

int main() {
    SetUnhandledExceptionFilter(WindowsExceptionHandler);
    std::set_terminate(TerminateHandler);
    throw std::runtime_error("BAR");
}
Run Code Online (Sandbox Code Playgroud)

输出:

FOO
Run Code Online (Sandbox Code Playgroud)

我希望它输出BAR或者FOOBAR

注释掉SetUnhandledExceptionFilter使其工作(但这是不可接受的,因为它不会捕获其他 Windows 异常类型)。

显然以某种方式SetUnhandledExceptionFilter覆盖std::set_terminate

RbM*_*bMm 5

所有 C++ 异常内部都使用throw关键字。它内部使用_CxxThrowException此 api 调用RaiseException函数并0xE06D7363就地dwExceptionCode。因此,SetUnhandledExceptionFilter如果想用TerminateHandler.

g_prevlpTopLevelExceptionFilter = SetUnhandledExceptionFilter(WindowsExceptionHandler);
Run Code Online (Sandbox Code Playgroud)

if (ExceptionRecord->ExceptionCode == 0xE06D7363) {
    return g_prevlpTopLevelExceptionFilter(ep);
}
Run Code Online (Sandbox Code Playgroud)
LPTOP_LEVEL_EXCEPTION_FILTER g_prevlpTopLevelExceptionFilter;

LONG WINAPI WindowsExceptionHandler(LPEXCEPTION_POINTERS ep) {

    PEXCEPTION_RECORD ExceptionRecord = ep->ExceptionRecord;

    printf("%s: %x at %p", __FUNCTION__, 
        ExceptionRecord->ExceptionCode, ExceptionRecord->ExceptionAddress);

    if (ULONG NumberParameters = ExceptionRecord->NumberParameters)
    {
        printf(" { ");
        PULONG_PTR ExceptionInformation = ExceptionRecord->ExceptionInformation;
        do 
        {
            printf(" %p", (void*)*ExceptionInformation++);
        } while (--NumberParameters);
        printf(" } ");
    }

    printf("\n");

    if (ExceptionRecord->ExceptionCode == 0xE06D7363) {
        return g_prevlpTopLevelExceptionFilter(ep);
    }

    return EXCEPTION_EXECUTE_HANDLER;
}

void TerminateHandler() {
    MessageBoxW(0, 0, __FUNCTIONW__, MB_ICONWARNING);
    exit(-1);
}

void main() {
    g_prevlpTopLevelExceptionFilter = 
        SetUnhandledExceptionFilter(WindowsExceptionHandler);
    set_terminate(TerminateHandler);
    throw "888";
}
Run Code Online (Sandbox Code Playgroud)