Reputation: 131636
C++23 will likely see the introduction of a stack trace mechanism, via the <stacktrace>
header.
I know we're going to have an std::stack_trace
class, made up of std::stacktrace_entry
'ies, and that is all fine. But - this won't be much help by just existing, because everyone would have to painstakingly make sure they always collect a stack trace and put it in the exception they throw. That is... not good.
Instead, what I want is for every (?) exception to automatically carry a stack trace, so that when I examine it or print it, or even when it gets auto-printed when not caught, the stack trace will be printed out.
Is this planned for to be possible, or am I asking too much?
Upvotes: 7
Views: 1915
Reputation: 131636
This is not a definitive answer, but there's a proposal P2370: Stack Trace from Exception / Polukhin & Nekrashevich for allowing basically what you want. This was proposed in August 2021, and did not make it into C++23, but may make it into C++26 (see GitHub for status).
It would let you write:
try {
foo("test1");
bar("test2");
} catch (const std::exception& ex) {
std::stacktrace trace = std::stacktrace::from_current_exception(); // <---
std::cerr << "Caught exception: " << ex.what() << ", trace:\n" << trace;
}
There's a question of whether or not to turn this on by default. There could be something like:
std::this_thread::set_capture_stacktraces_at_throw(bool enable) noexcept;
which you need to call to make it happen.
Upvotes: 10
Reputation: 1048
As einpoklum said there is currently no way to do this for every exception object automatically.
But you can make a custom traced exception object that embeds a stack trace when thrown and use this throughout your code. This can be implemented with std::stacktrace
or you could use a library like cpptrace which implements traced exceptions for C++11 and up.
Upvotes: 1