Nathaniel Flath
Nathaniel Flath

Reputation: 16015

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?

Upvotes: 3

Views: 243

Answers (1)

Mykola
Mykola

Reputation: 3363

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

Upvotes: 4

Related Questions