简体   繁体   中英

C++ disable exceptions below stack frame

Is there a way to cause an exception to not propagate above a certain stack frame, while not losing stack information?

IE,

int foo() {
   throw 3;
}

int bar() {
   // do something here
   foo();
}

int main() {
   try {
      bar();
   } catch(...) {
      std::cout << "Caught";
   }
}

I want this to terminate at the 'throw 3' call, without being able to be caught by main.

is this possible?

Simply add throw() after functions declaration and definition

#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
      }
}

this will block your throw calls

stack trace function in different os

backtrace_symbols(3) - linux, mac osx

CaptureStackBackTrace(...) - windows

Live demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM