Re: Exceptions, Go to Hell!
Goran Pusic wrote:
On Aug 26, 10:26 am, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
I am curious: if I use a function that communicates failure (or some
other condition) via throwing, how can RAII or ScopeGuard help me to
avoid a catch statement?
Well... I __guessed__ that OP who complained about try/catch had too
many of them (perhaps I was wrong), and that they were caused by the
following situations:
{
TYPE r = alloc(); // r holds a resource; we must free it at the
block end.
workworkwork(); might throw, or simply return prematurely
free(r);
}
so you'd do:
{
TYPE r = alloc();
try
{
workworkwork();
free(r);
}
catch(...)
{
free(r); // must be a no-throw operation.
throw;
}
}
This alone is ugly, now imagine that you have another (or more)
resources in that block.
So, if you use RAII (that is, have resource-wrapper class for TYPE),
or scope guard, try/catch-es like above all disappear (as well as
multiple calls to free).
I see, you worry about the catch block that is not concerned with actually
dealing with the exception thrown by workworkwork(). That's why you rethrow.
You still need to catch the exception from workworkwork() and handle it
proper. What RAII gives you is automatic resource management during stack
unwinding.
The number of "other types" of try/catch statements in code is IMO
very, very small. And the bigger the code base, the smaller it is
(compared to said size).
Hm, I am not so sure about that. It very much depends on how religiously and
locally you handle exceptions. On one extreme end, you let everything
propagate to the top-level and have one catch-all block. On the other end of
the spectrum, you can handle each exception as early as possible. In the
later case, you will still have a sizable number of catch blocks.
Best
Kai-Uwe Bux