Re: Error handling idioms
* jeffc226@yahoo.com:
I'm interested in an idiom for handling errors in functions without
using traditional nested ifs, because I think that can be very awkward
and difficult to maintain, when the number of error checks gets about
3 or so. It also gets very awkward in nested loops, where you want to
check for normal loop processing in the loop condition, not errors.
Yes, you could put some generic exit flag in the loop condition, but
when you're simply done if you find an error, it's much more
straightforward to simply leave all of it.
Exceptions would work, but that is inconsistent with the principle
that exceptions be used for exceptional cases, i.e. errors that you
don't expect could occur.
Don't let silly principles get in the way of practicality.
Basically what I have in mind is something using multiple return
points from a function and possibly gotos (both inconsistent with
traditional structured programming).
Single-entry-multiple-exit (SEME) is advocated by many C++ experts,
including Andrei Alexandrescu.
Some people (e.g. me) have argued to the contrary.
But that's just to flesh out possible shortcomings; don't let silly
principles get in the way of practicality.
This seems good to me - thoughts?
The below code is absolutely ungood: it's not exception safe.
Use C++ destructors for cleanup (called RAII).
Then just use 'return' to return.
Further links for reading?
Look up Petru Marginean and Andrei Alexandrescu's scope guard article.
bool f()
{
if (error condition)
goto ERROR_RETURN;
// do stuff
for ...
{
for ...
{
// do stuff
if (error condition)
goto ERROR_RETURN;
}
}
if (error condition)
goto ERROR_RETURN;
return true;
ERROR_RETURN:
// do some cleanup
return false;
}
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?