On Tue, 22 Jun 2010 13:12:33 -0400, Joseph M. Newcomer
<newcomer@flounder.com> wrote:
I'm not sure this is a good piece of advice. I use try/catch a lot; it is
essentially a
"non-local GOTO", a structured way of aborting execution and returning to
a known place,
while still guaranteeing that all intermediate destructors for stack
variables are called.
It is particularly useful in writing tasks like recursive-descent parsers
(particularly if
you just want to stop without trying to do error recovery, which is always
hard) and
terminating threads while still guaranteeing that you return from the
top-level thread
function. It is clean and well-structured way of aborting a
partially-completed
operation. An it is the only way to report errors from operations like
'new'. Also, look
at the number of exceptions that can be thrown by std:: or boost::.
Goran was not saying exceptions are bad, just that overly frequent use of
try/catch is bad, which it usually is. I've been saying for a long long
time that there's an inverse relationship between the number of try/catch
clauses you have and the effectiveness with which you're using exceptions.
There are a number of reasons for this. On the API designer side, using
exceptions where return codes are more appropriate forces callers to write
try/catch whenever they use the function, so that's a bad use of
exceptions. You never want to turn exception usage into a clumsier version
of return codes. On the user side, try/catch gets overused when people
don't employ the RAII idiom and need to perform clean-up that should be
handled by a destructor. Ideally, exceptions are caught far away from
where
they're thrown, in a top-level handler, which reports the error to the
user, logs it, or whatever. It is relatively rare for well-designed code
to
need to handle the exception closer to the throw-point.
many exceptions are thrown. Exceptions are not meant as a "non-local GOTO".
'exceptional' conditions!), not normal control flow. I once saw a switch
statement rewritten as a bunch of thrown exceptions, not a pretty sight.