A
Alan Johnson
FAQ 17.3 says: "never throw an exception from a destructor while
processing another exception"
What mechanism is available for me to know if an exception is being
processed?
I imagine this knowledge being useful in a case like the following. You
have an operation that needs to be done in pairs (e.g. locking and
unlocking a Mutex). To make life easier, you create a class to do these
for you when you enter/leave a scope. The action to be performed when
leaving a scope, however, can throw an exception. So you may want to do
something like:
class Guard
{
private:
Mutex & m_mutex ;
public:
explicit Guard(Mutex & mutex) : m_mutex(mutex)
{
m_mutex.lock() ;
}
~Guard()
{
try
{
m_mutex.unlock() ;
}
catch (...)
{
if (/* Not processing another exception. */)
throw ;
/* Maybe do some logging or something here. */
}
}
} ;
processing another exception"
What mechanism is available for me to know if an exception is being
processed?
I imagine this knowledge being useful in a case like the following. You
have an operation that needs to be done in pairs (e.g. locking and
unlocking a Mutex). To make life easier, you create a class to do these
for you when you enter/leave a scope. The action to be performed when
leaving a scope, however, can throw an exception. So you may want to do
something like:
class Guard
{
private:
Mutex & m_mutex ;
public:
explicit Guard(Mutex & mutex) : m_mutex(mutex)
{
m_mutex.lock() ;
}
~Guard()
{
try
{
m_mutex.unlock() ;
}
catch (...)
{
if (/* Not processing another exception. */)
throw ;
/* Maybe do some logging or something here. */
}
}
} ;