How to get what () and back track at the same time for an uncaught exception?

When an uncaught exception occurs in my application, I can get the what() exception by adding a global catch function to my main() , something like:

 catch (std::exception& ex) { std::cerr << "Error: " << ex.what() << "\n"; } 

I can also get a trace of the location stack where the exception was thrown by calling backtrace() and backtrace_symbol() from the std::terminate() handler (set by calling std::set_terminate() ). For example (ignore memory leak):

 void terminate_handler() { void** buffer = new void*[15]; int count = backtrace(buffer, 15); backtrace_symbols_fd(buffer, count, STDERR_FILENO); } … std::set_terminate(terminate_handler); 

But when I try to combine the two approaches by reconfiguring the exception using throw; in my global catch , I get a stack trace to this catch , and not to the place where the exception was originally thrown.

Is there a way I can do both (get the stack trace for the place where the exception was originally thrown, and also get its what() value)?

+7
c ++ gcc exception
source share
1 answer

This should work:

 void terminate_handler() { void** buffer = new void*[15]; int count = backtrace(buffer, 15); backtrace_symbols_fd(buffer, count, STDERR_FILENO); //etc. auto ptr = std::current_exception(); try { std::rethrow_exception(ptr); } catch (std::exception & p) { std::cout << p.what() << std::endl;} } 
+1
source share

All Articles