Boost logo

Boost :

From: Rob Stewart (stewart_at_[hidden])
Date: 2004-05-28 08:48:25


From: "E. Gladyshev" <eegg_at_[hidden]>
>
> Your solution
>
> try{...}
> catch(...)
> {
> try { throw; }
> catch( type1 ) { ... }
> }
>
> is very different from
>
> try{...}
> catch( type1 ) {...}
>
> One of the differences is that in the first case, the stack unwinding will
> be
> triggered for any exception. In the second case, it is not necessarily the
> case.

Not at all. From 15.2/1:

   As control passes from a throwexpression to a handler,
   destructors are invoked for all automatic objects constructed
   since the try block was entered.

In order to enter any handler, stack unwinding occurs. In the
first case, stack unwinding occurs immediately because "catch
(...)" matches all exceptions. In the second case, only if there
wasn't a handler for a particular exception would stack unwinding
be delayed while the search continued for another handler
(including unexpected()). IOW, stack unwinding will occur for
both forms, it's just a question as to where the handler will be
found.

Let me make this more concrete. Assume the only expected
excceptions are type1, type2, and type3. Then this:

try { ... }
catch (...)
{
   // stack unwinding has occurred by the time we get here
   // this is actually in a separate function, of course
   try
   {
      throw;
   }
   catch (type1 const &) { ... }
   catch (type2 const &) { ... }
   catch (type3 const &) { ... }
   catch (...)
   {
      throw;
   }
}

does exactly the same thing, wrt stack unwinding, as this:

try { ... }
catch (type1 const &)
{
   // stack unwinding has occurred by the time we get here
   ...
}
catch (type2 const &)
{
   // stack unwinding has occurred by the time we get here
   ...
}
catch (type3 const &)
{
   // stack unwinding has occurred by the time we get here
   ...
}

If the function called by the first form handles a different set
of exceptions, then the only change is where the handler is for
the active exception. Stack unwinding will have occurred by the
time that handler is entered. If both forms provide the same set
of handlers, then the only difference is where the handler is
found.

Given that the former approach captures common exception handling
in a single function that rethrows the exception, it is merely
shorthand for having to write the same handlers repeatedly.

-- 
Rob Stewart                           stewart_at_[hidden]
Software Engineer                     http://www.sig.com
Susquehanna International Group, LLP  using std::disclaimer;

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk