views:

163

answers:

5

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?

A: 

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

Mike McQuaid
A: 
A: 

You may be looking for

// Returns true only if a thrown exception is being currently processed
namespace std {
    bool uncaught_exception();
};

http://msdn.microsoft.com/en-us/library/k1atwat8.aspx

RaphaelSP
+3  A: 

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 http://msdn.microsoft.com/en-us/library/k1atwat8%28VS.71%29.aspx

Diaa Sami
This works perfectly, I must have been Googling with the wrong keywords not to spot this. :)
pauldoo
Note that while this tells you whether an exception is in flight, knowledge of that fact is almost never useful. In particular, when used in a destructor it does not tell you whether you can/should throw an exception on failure: http://www.gotw.ca/gotw/047.htm
Steve Jessop
Destructors should simply never ever throw any exceptions.
Rob K
+3  A: 

Before you go too far down the uncaught_exception() path, look at http://www.gotw.ca/gotw/047.htm

Joel