How will I throw exceptions with stack traces in C++23?

Viewed 312

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 got.

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?

1 Answers

Not a definitive answer, but there's a proposal for allowing basically what you want:

Paper 2370: Stack Trace from Exception / Polukhin & Nekrashevich

This was proposed a few months ago (August 2021). 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;
}

but 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.

Edit: Unfortunately, this won't happen in C++2023; possibly in 2026.

Related