Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

exception

gcc

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

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

I can also get the stack trace of the location where the exception was thrown by calling backtrace() and backtrace_symbol() from inside a std::terminate() handler (set by calling std::set_terminate()). For example (ignore the 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 rethrowing the exception using throw; in my global catch, I'm getting stack trace to that catch, not to the location where the exception was originally thrown.

Is there some way I can do both (get the stack trace for the location where the exception was originally thrown and also get the value of its what()) at the same time?

like image 601
svick Avatar asked Sep 18 '13 15:09

svick


1 Answers

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;}
}
like image 143
sbabbi Avatar answered Sep 21 '22 11:09

sbabbi