How to check from destructor whether it was called due to exception or normal exit from the scope?

I

Igor Tandetnik

Alexander Grigoriev said:
If you want to log exceptions in critical places, write a class with a
member function to call at the scope end. If the function was not
called, the execution haven't reached the point, it means the
exception was thrown. The destructor then logs a record.

This idiom is known as Scope Guard. For an extensive treatment of these,
see

http://www.cuj.com/documents/s=8000/cujcexp1812alexandr/alexandr.htm

--
With best wishes,
Igor Tandetnik

"For every complex problem, there is a solution that is simple, neat,
and wrong." H.L. Mencken
 
A

Antonio

This small object is especially designed for the sole purpose of debug
logging. It doesn't allocate or deallocate any resources, roughly it simply
outputs in its constructor time, thread id and the fact that we entered the
scope; in its destructor it outputs time, thread id and the fact that we
left the scope. At the beginning of those functions and methods that have to
be traced we simply declare a local variable of this type and it does all
the job we need (one line of code, present only in Debug builds that will be
easily eliminated in Release builds).

Now if we start using catch clauses, we'll have to write a whole bunch of
code, which we don't want to have in Release builds at all cause it is only
used for debugging purposes. With the second argument (calling a member
function at the end) there is also inconvenience: there can be multiple
returns from the function and we don't want to duplicate code that sets flag
about reaching scope end before each return statement. This is error prone
because new developer might forget or do not know that he has to copy
something before each return and this in turn will mislead other developers
who might need to dig later in debug logs.

Actually this class is already extensively used by us and what we want is
just to add to it ability to log in destructor that it was called due to
stack unwind (we want to do this in its destructor, not in the places where
this object will be instantiated, because we don't want our code to be
obstructed by debug logging). This is not an impossible task and with proper
implementation of standard library's std::uncaught_exception() in MSVC++ 6
we would have been able to do this. However MSVC++ 6.0 SP6 implements
std::uncaught_exception() as return false; so what we are looking for is for
reliable workaround that can give us the same result as
std::uncaught_exception() when compiled under MSVC++ 6.0.

Kind regards,
Antonio
 

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

Top