Windows __try/__except 没有捕获引发的异常

Windows __try/__except doesn't catch raised exceptions

所以我试图写一些取消引用未知指针和 returns 操作状态的东西,就像这样:

int n;
__try {
    n = *(int*)(addr); // The unknown address.
}
__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
    printf("Exception caught!\n");
}

现在这段代码甚至没有在第一时间捕捉到异常,所以 VS 调试器反而捕捉到了它。所以我很好奇,做了一个简单的干 运行:

__try {
    RaiseException(EXCEPTION_ACCESS_VIOLATION, NULL, NULL, nullptr);
}
__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
    printf("Exception caught!\n");
}

这产生了与其他代码块相同的结果。尽管我已经将上面的代码块写了数百次,但我真的不确定为什么 __try 会突然假装它根本不存在。是的,我检查了我的编译器设置。它们被设置为使用 /RTC1 进行编译。

正如@Hans Passant 所说,进程的调试器可以在基于帧的异常处理程序之前捕获异常(我检查过)。
RaiseException 列出异常处理程序序列。

  1. The system first attempts to notify the process's debugger, if any.
  2. If the process is not being debugged, or if the associated debugger does not handle the exception, the system attempts to locate a frame-based exception handler by searching the stack frames of the thread in which the exception occurred. The system searches the current stack frame first, then proceeds backward through preceding stack frames.
  3. If no frame-based handler can be found, or no frame-based handler handles the exception, the system makes a second attempt to notify the process's debugger.
  4. If the process is not being debugged, or if the associated debugger does not handle the exception, the system provides default handling based on the exception type. For most exceptions, the default action is to call the ExitProcess function.