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?
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;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With