c++禁止堆栈框架下的异常

C++ disable exceptions below stack frame

本文关键字:异常 框架 禁止 堆栈 c++      更新时间:2023-10-16

是否有一种方法可以使异常不传播到某个堆栈帧之上,同时不丢失堆栈信息?

,

int foo() {
   throw 3;
}
int bar() {
   // do something here
   foo();
}
int main() {
   try {
      bar();
   } catch(...) {
      std::cout << "Caught";
   }
}

我希望这个在'throw 3'调用时终止,而不能被main捕获。

这可能吗?

只需在函数声明和定义后添加throw()

#include <iostream>
void* g_pStackTrace = NULL;
int foo() throw();
int foo() throw() {
   g_pStackTrace = <stack_trace_function_call>;
   throw 3;
}
int bar() {
   // do something here
   foo();
   return 0;
}
int main() {
      bar();
      if (g_pStackTrace != NULL)
      {
           // Work with our stack
      }
}

这将阻止你的throw调用

不同操作系统的堆栈跟踪函数

backtrace_symbols(3) - linux, mac osx

CaptureStackBackTrace(...) - windows

现场演示