我遇到了一个问题,我传递给 SetUnhandledExceptionFilter 的函数当异常代码 c0000374 引发时没有被调用。但它适用于异常代码 c0000005。 然后我尝试使用 AddVectoredExceptionHandler相反,它没有问题,处理函数被正确调用。
是 API 错误吗?我可以到处使用 AddVectoredExceptionHandler 而不是 SetUnhandledExceptionFilter 吗?
这两个函数都可以正常工作
// Exception code c0000005
int* p1 = NULL;
*p1 = 99;
只有 AddVectoredExceptionHandler 可以捕获此异常。 (为了证明它不依赖于运行时库,我手动引发了异常,结果是一样的。)
// Exception code c0000374
RaiseException(0xc0000374, 0, 0, NULL);
测试程序。
#include <tchar.h>
#include <fstream>
#include <Windows.h>
LONG WINAPI VectoredExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)
{
std::ofstream f;
f.open("VectoredExceptionHandler.txt", std::ios::out | std::ios::trunc);
f << std::hex << pExceptionInfo->ExceptionRecord->ExceptionCode << std::endl;
f.close();
return EXCEPTION_CONTINUE_SEARCH;
}
LONG WINAPI TopLevelExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)
{
std::ofstream f;
f.open("TopLevelExceptionHandler.txt", std::ios::out | std::ios::trunc);
f << std::hex << pExceptionInfo->ExceptionRecord->ExceptionCode << std::endl;
f.close();
return EXCEPTION_CONTINUE_SEARCH;
}
int _tmain(int argc, _TCHAR* argv[])
{
AddVectoredExceptionHandler(1, VectoredExceptionHandler);
SetUnhandledExceptionFilter(TopLevelExceptionHandler);
// Exception code c0000374
RaiseException(0xc0000374, 0, 0, NULL);
// Exception code c0000005
// int* p1 = NULL;
// *p1 = 99;
return 0;
}
最佳答案
这是因为 MSVC CRT 启动中的这段代码:
/*
* Enable app termination when heap corruption is detected on
* Windows Vista and above. This is a no-op on down-level OS's
* and enabled by default for 64-bit processes.
*/
if (!_NoHeapEnableTerminationOnCorruption)
{
HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
}
如果您想禁用它(不推荐),请将 nohetoc.obj
链接到您的程序。
关于c++ - 为什么 SetUnhandledExceptionFilter 无法捕获某些异常但 AddVectoredExceptionHandler 可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19656946/