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
2009-07-27 11:42:30
A:
You may be looking for
// Returns true only if a thrown exception is being currently processed
namespace std {
bool uncaught_exception();
};
RaphaelSP
2009-07-27 13:31:20
+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
2009-07-27 13:32:55
This works perfectly, I must have been Googling with the wrong keywords not to spot this. :)
pauldoo
2009-07-27 14:45:10
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
2009-07-27 14:50:54
Destructors should simply never ever throw any exceptions.
Rob K
2009-07-27 17:42:32
+3
A:
Before you go too far down the uncaught_exception() path, look at http://www.gotw.ca/gotw/047.htm
Joel
2009-07-27 16:55:29