Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ disable exceptions below stack frame

Tags:

c++

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?

like image 796
Nathaniel Flath Avatar asked Dec 08 '25 22:12

Nathaniel Flath


1 Answers

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

like image 173
Mykola Avatar answered Dec 10 '25 13:12

Mykola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!