How to detect when an exception is in flight?

0 votes
asked Jul 27, 2009 by pauldoo

In C++ (MSVC) how can I test whether an exception is currently "in flight". Ie, code which is being called as part of a class destructor may be getting invoked because an exception is unwinding the stack.. How can I detect this case as opposed to the normal case of a destructor being called due to a normal return?

5 Answers

0 votes
answered Jul 27, 2009 by mike-mcquaid

I'm not sure if there's a better way but could you not catch and rethrow the exception?

0 votes
answered Jul 27, 2009 by deemok

one way would to replace the exception handling machinery with your own.

on the other hand, it always begs for the question - why would one want to do that?..

a few more links on the subj: Reversing Microsoft Visual C++ Part I: Exception Handling and The exception model

0 votes
answered Jul 27, 2009 by diaa-sami

Actually it's possible to do this, call uncaught_exception() in <exception> header. One reason you might want to do this is before throwing an exception in a destructor, which would lead to program termination if this destructor was called as part of stack unwinding. See

0 votes
answered Jul 27, 2009 by joel

Before you go too far down the uncaught_exception() path, look at

0 votes
answered Sep 15, 2017 by paul-groke

In C++17, std::uncaught_exceptions (note the plural "s") was introduced. This allows you to capture the "nested unwinding" count in the ctor and compare the captured value to the current value when the dtor is executed. That way you can know if your object is being destroyed because its scope was left by means of an exception (dtor current value > captured value).

Which means you can finally implement stuff like "auto-undo" guards in C++, yay. :)

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter