473,243 Members | 1,522 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,243 software developers and data experts.

Exceptions vs. Error Codes

I know this is a recurring discussion (I've spent the last 3 days
reading through threads on the topic), but I feel compelled to start
it up again.

After reading through the existing threads, I find myself convinced
that exceptions are a better mechanism, for example because
constructors and operators can't return errors, and code that doesn't
need to handle/translate/recover in the face of errors, but can just
propagate the error is cleaner with exceptions.

However, those reasons are often not compelling enough to convince
people who don't like exceptions (usually in my experience because
they incorrectly think that exceptions are more 'dangerous' somehow
than error codes, when in fact, they just don't see that it is just as
dangerous to ignore an error code as it is to not handle an exception
when it should be).

Consider this idiom when using error codes:

ErrorCode EcFoo()
{
ErrorCode ec;
Check(EcBar());
Check(EcBletch());
...
Exit:
return (ec);
}

Here, Check is a macro that checks the return code and jumps to Exit
if an error occurs.

Using this pattern, we avoid the appearance of a slew of if/then
statments (although they are there, of course, just hidden by the
preprocessor).

This makes the code almost as straightforward as the exception case,
and doesn't introduce much overhead (space or time), since it is
basically just adding a check for 0 to each call.

This addresses some of the problems I've seen leveled against error
codes. Although it seems to me that we're just writing what amounts to
our own equivalent to exceptions here (for example, functions that
don't handle the error don't need to do any 'additional' work to
propagate the error, assuming they are following the pattern), some
people are more comfortable with this because they know that returning
and checking for error codes is always fairly inexpensive, while
throwing an exception can be expensive.

Any specific thoughts on the idiom, or compelling arguments to offer
for the use of exceptions to the reluctant?
Jul 22 '05 #1
8 3535

"Shane Groff" <sh***@shaneandsusan.com> wrote in message
news:78**************************@posting.google.c om...
I know this is a recurring discussion (I've spent the last 3 days
reading through threads on the topic), but I feel compelled to start
it up again.

After reading through the existing threads, I find myself convinced
that exceptions are a better mechanism, for example because
constructors and operators can't return errors, and code that doesn't
need to handle/translate/recover in the face of errors, but can just
propagate the error is cleaner with exceptions.

However, those reasons are often not compelling enough to convince
people who don't like exceptions (usually in my experience because
they incorrectly think that exceptions are more 'dangerous' somehow
than error codes, when in fact, they just don't see that it is just as
dangerous to ignore an error code as it is to not handle an exception
when it should be).

Consider this idiom when using error codes:

ErrorCode EcFoo()
{
ErrorCode ec;
Check(EcBar());
Check(EcBletch());
...
Exit:
return (ec);
}

Here, Check is a macro that checks the return code and jumps to Exit
if an error occurs.

Using this pattern, we avoid the appearance of a slew of if/then
statments (although they are there, of course, just hidden by the
preprocessor).

This makes the code almost as straightforward as the exception case,
and doesn't introduce much overhead (space or time), since it is
basically just adding a check for 0 to each call.

This addresses some of the problems I've seen leveled against error
codes. Although it seems to me that we're just writing what amounts to
our own equivalent to exceptions here (for example, functions that
don't handle the error don't need to do any 'additional' work to
propagate the error, assuming they are following the pattern), some
people are more comfortable with this because they know that returning
and checking for error codes is always fairly inexpensive, while
throwing an exception can be expensive.

Any specific thoughts on the idiom, or compelling arguments to offer
for the use of exceptions to the reluctant?


One obvious disadvantage of your 'error code' solution is that
it doesn't implement 'stack unwinding' i.e. automatic destruction,
whereas exceptions do.

-Mike
Jul 22 '05 #2
* Shane Groff:
I know this is a recurring discussion (I've spent the last 3 days
reading through threads on the topic), but I feel compelled to start
it up again.

After reading through the existing threads, I find myself convinced
that exceptions are a better mechanism, for example because
constructors and operators can't return errors
Constructors can produce error codes. A constructor can take a reference
or pointer argument, or it can store an error code somewhere else. One
main reason why that is not a _good idea_ is that the built-in mechanism
for cleaning up when an objected is allocated dynamically and the
constructor fails, requires an exception from the constructor, and that
similar techniques implemented by oneself have the same requirement; without
such automated cleanup there is a live but invalid object around.

Another main reason is that the approach is not general: additional arguments
cannot be tacked on to a copy constructor or, as you write, an operator, so
these would have to store their error codes in some accessible place.

The "live but invalid" argument is also the main argument for not using
two-phase construction (except when encapsulated by an object factory).

and code that doesn't
need to handle/translate/recover in the face of errors, but can just
propagate the error is cleaner with exceptions.
Yup.

However, those reasons are often not compelling enough to convince
people who don't like exceptions (usually in my experience because
they incorrectly think that exceptions are more 'dangerous' somehow
than error codes, when in fact, they just don't see that it is just as
dangerous to ignore an error code as it is to not handle an exception
when it should be).

Consider this idiom when using error codes:

ErrorCode EcFoo()
{
ErrorCode ec;
Check(EcBar());
Check(EcBletch());
...
Exit:
return (ec);
}

Here, Check is a macro that checks the return code and jumps to Exit
if an error occurs.


Macros are evil.

An alternative is to make the error code an object that requires a check()
or value() or succeeded() call or something in order not to throw an
exception.

Some folks have advocated that approach e.g. because it makes the code more
explicit; one main drawback is that all code everywhere must then check every
function call for possible error, giving C-style impenetrable code, and
another main drawback is that exceptions are needed for constructors and
such anyway, lest one wind up with "live but invalid" objects...

--
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?
Jul 22 '05 #3
"Mike Wahler" <mk******@mkwahler.net> wrote in message news:<z9***************@newsread3.news.pas.earthli nk.net>...
"Shane Groff" <sh***@shaneandsusan.com> wrote in message
news:78**************************@posting.google.c om...
Consider this idiom when using error codes:

ErrorCode EcFoo()
{
ErrorCode ec;
Check(EcBar());
Check(EcBletch());
...
Exit:
return (ec);
}

Here, Check is a macro that checks the return code and jumps to Exit
if an error occurs.
Any specific thoughts on the idiom, or compelling arguments to offer
for the use of exceptions to the reluctant?


One obvious disadvantage of your 'error code' solution is that
it doesn't implement 'stack unwinding' i.e. automatic destruction,
whereas exceptions do.

-Mike


I'm not sure I understand. If I have local objects within the
function, they will be destroyed when the function exists whether the
exit is through a normal return, or an exception. If every function
is written along the pattern above, then each function jumps to the
return and passes the error code back up the chain, and local objects
are destroyed when the function returns.
Jul 22 '05 #4

"Shane Groff" <sh***@shaneandsusan.com> wrote in message
news:78**************************@posting.google.c om...
I know this is a recurring discussion (I've spent the last 3 days
reading through threads on the topic), but I feel compelled to start
it up again.

After reading through the existing threads, I find myself convinced
that exceptions are a better mechanism, for example because
constructors and operators can't return errors, and code that doesn't
need to handle/translate/recover in the face of errors, but can just
propagate the error is cleaner with exceptions.

However, those reasons are often not compelling enough to convince
people who don't like exceptions (usually in my experience because
they incorrectly think that exceptions are more 'dangerous' somehow
than error codes, when in fact, they just don't see that it is just as
dangerous to ignore an error code as it is to not handle an exception
when it should be).
I think your reasoning is spot on. I've seem many examples where code
appears to be checking for errors because there are loads of if statements
checking return values (often this is the bulk of the code!) but when you
actually test it doesn't work because somewhere in the chain of function
calls a return value check was missed, or because the code has been hacked
around the cleanup after detecting an error doesn't work correctly.

Consider this idiom when using error codes:

ErrorCode EcFoo()
{
ErrorCode ec;
Check(EcBar());
Check(EcBletch());
...
Exit:
return (ec);
}

Here, Check is a macro that checks the return code and jumps to Exit
if an error occurs.


In C++ you are not allowed to jump over a declaration. So this would force
you into C style code where all the declarations are at the start of a
block.

john
Jul 22 '05 #5

"Shane Groff" <sh***@shaneandsusan.com> schrieb im Newsbeitrag
news:78**************************@posting.google.c om...
"Mike Wahler" <mk******@mkwahler.net> wrote in message news:<z9***************@newsread3.news.pas.earthli nk.net>...
"Shane Groff" <sh***@shaneandsusan.com> wrote in message
news:78**************************@posting.google.c om...
Consider this idiom when using error codes:

ErrorCode EcFoo()
{
ErrorCode ec;
Check(EcBar());
Check(EcBletch());
...
Exit:
return (ec);
}

Here, Check is a macro that checks the return code and jumps to Exit
if an error occurs.
Any specific thoughts on the idiom, or compelling arguments to offer
for the use of exceptions to the reluctant?


One obvious disadvantage of your 'error code' solution is that
it doesn't implement 'stack unwinding' i.e. automatic destruction,
whereas exceptions do.


I'm not sure I understand. If I have local objects within the
function, they will be destroyed when the function exists whether the
exit is through a normal return, or an exception. If every function
is written along the pattern above, then each function jumps to the
return and passes the error code back up the chain, and local objects
are destroyed when the function returns.


You are right. The stackunwinding is only needed when you throw an exception
somewhere several levels deep in a callstack and the exception hanling need
to unwind all these calls in progress. In your sample this is not a problem.
I think goto would not allow this anyway.
Regards
Michael
Jul 22 '05 #6

"Shane Groff" <sh***@shaneandsusan.com> schrieb im Newsbeitrag
news:78**************************@posting.google.c om...

Consider this idiom when using error codes:

ErrorCode EcFoo()
{
ErrorCode ec;
Check(EcBar());
Check(EcBletch());
...
Exit:
return (ec);
}

Here, Check is a macro that checks the return code and jumps to Exit
if an error occurs.

Using this pattern, we avoid the appearance of a slew of if/then
statments (although they are there, of course, just hidden by the
preprocessor).

This makes the code almost as straightforward as the exception case,
and doesn't introduce much overhead (space or time), since it is
basically just adding a check for 0 to each call.

This addresses some of the problems I've seen leveled against error
codes. Although it seems to me that we're just writing what amounts to
our own equivalent to exceptions here (for example, functions that
don't handle the error don't need to do any 'additional' work to
propagate the error, assuming they are following the pattern), some
people are more comfortable with this because they know that returning
and checking for error codes is always fairly inexpensive, while
throwing an exception can be expensive.

Any specific thoughts on the idiom, or compelling arguments to offer
for the use of exceptions to the reluctant?


I have seen these kind of error handling many times in code, but somehow I
never liked the necessary goto statement.
So I never used it myself.

When I have to decide if I should use exception handling or error codes I
have mostly the following things in mind:
- Error codes are self documenting whereas exceptions are not.
- Exceptions are slower so if its within performance critical code I dont
want to open a try/catch block all the time.
- Exception lead to a cleaner caller code.
- C++ constructs throw exceptions themselfes (new) so If not using
exceptions as error communication these should be converted to error codes
or avoided (hard to achieve), which is quite an effort and a possible
performance problem again .
- Make code (caller) exception safe requires some knowledge. After reading
Herb Sutters "Exceptional C++" I wondered why my programs ever worked
properly ;-)
IMHO at the end its a mixture of the requirements your code has to foolfill
and a bit of personal taste.

Best Regards
Michael


Jul 22 '05 #7

"Michael Kurz" <m.****@inode.at> schrieb im Newsbeitrag
news:41********@e-post.inode.at...

IMHO at the end its a mixture of the requirements your code has to

foolfill

sorry, meant fulfill of course. :-)


Jul 22 '05 #8

"Shane Groff" <sh***@shaneandsusan.com> wrote in message
news:78**************************@posting.google.c om...
"Mike Wahler" <mk******@mkwahler.net> wrote in message news:<z90ad.758
One obvious disadvantage of your 'error code' solution is that
it doesn't implement 'stack unwinding' i.e. automatic destruction,
whereas exceptions do.

-Mike


I'm not sure I understand. If I have local objects within the
function, they will be destroyed when the function exists whether the
exit is through a normal return, or an exception. If every function
is written along the pattern above, then each function jumps to the
return and passes the error code back up the chain, and local objects
are destroyed when the function returns.


Right. But with exceptions, you don't need to write anything.
Just throw the exception and it 'just works'.

-Mike
Jul 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Mark Oueis | last post by:
I've been struggling with this question for a while. What is better design? To design functions to return error codes when an error occures, or to have them throw exceptions. If you chose the...
9
by: Gianni Mariani | last post by:
I'm involved in a new project and a new member on the team has voiced a strong opinion that we should utilize exceptions. The other members on the team indicate that they have either been burned...
10
by: Jakob Bieling | last post by:
Hi, somehow the prejudice of exceptions being rather slow (compared to, ie. returning an error value and checking that) keeps sticking around .. at least around me. I guess this is also why I...
59
by: kk_oop | last post by:
Hi. I wanted to use exceptions to handle error conditions in my code. I think doing that is useful, as it helps to separate "go" paths from error paths. However, a coding guideline has been...
1
by: chen | last post by:
We're having an internal debate about the merits & demerits of returning status codes in the output message vs exceptions to signify errors in handling a Web method. The status code camp is...
4
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and...
29
by: mailforpr | last post by:
Sometimes, I can't think of any good reason why I should have the program's logic thrown an exception. Except for catching the exception and printing "Uh, oh" to the screen. I also think that in...
13
by: mike3 | last post by:
Hi. (crossposted because the program is in C++ and some C++-related elements are discussed, hence comp.lang.c++, plus general program design questions are asked, hence comp.programming.) I'm...
5
by: adam.timberlake | last post by:
I've just finished reading the article below which goes into some depth about exceptions. The article was rather lucid and so I understand how to implement it all, the thing I'm having trouble with...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.