r/cpp • • Apr 19 '26

Adding Stack Traces to All C++ Exceptions

https://werwolv.net/posts/cpp_exception_stacktraces/
120 Upvotes

27 comments sorted by

View all comments

Show parent comment

1

u/kniy Apr 20 '26

You are misunderstanding. Two-phase-unwinding first searches the stack for a matching catch-block; and then in the second phase unwinds the stack (calling destructors). By capturing the stack trace within the filter-expression, it's captured in the first phase before the stack is unwound. You still get the full stack where the exception was thrown, but you only pay for it when necessary.

1

u/mark_99 Apr 21 '26

Oh interesting, that does seem like an improvement. Does this only work on MSVC?

1

u/kniy Apr 21 '26

There doesn't seem to be any nice way like MSVC's exception filters, but I think at some point I saw something working on linux/libstdc++. I can't find it right now, but if I remember correctly, it involved hacking some RTTI implementation details to hook the "does the exception type match the catch-handler's type" check.