How do I know if an exception is being processed?

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. */
}
}
} ;
 
I

Ian Collins

Alan said:
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?
Save yourself a lot of trouble and don't throw exceptions from destructors.
 
J

Jerry Coffin

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?

That's what uncaught_exception() does -- sort of.
I imagine this knowledge being useful in a case like the following.

See:

http://www.gotw.ca/gotw/047.htm

You're characterized the utility of the information perfectly: it's
purely imaginary. Your code fits closely with how most people thought it
would be useful -- but it turns out it's a mistake, and I've yet to see
anybody come up with a way to use unaught_exception that was useful.
Likewise, there's really no way to let an exception escape for a dtor
without it potentially causing problems -- and the difference between
"potentially" and "inevitably" is essentially nonexistent.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top