[LC++]To try or not

Davide Bolcioni 9odb6x3rfr001 at sneakemail.com
Sat Sep 28 04:42:01 UTC 2002


David filiond at videotron.ca [mltuxcpp/linux-cpp list] wrote:
> I'm relatively comfortable with the syntax of exceptions.  The problem I 
> have is I'm still not sure when I should use them.
> 
> Is there some standard as too when function should use a return code 
> (ie. return an int) or when it should use exceptions?
> 
> I guess what I'm trying to say is, when do I do this:
> 
> if (foo() == -1)
> 	cout << "Error!" << endl;
> 
> And when do I do this:
> 
> try {
> 	foo();
> }
> catch (int i) {
> 	cout << "Error, code: " << i << endl;
> }

The usual advice is to use error *returns* (not error codes)
when:
- the "error" is not really an error but a condition which is
   somewhat likely, e.g. end of a stream (you always get to the
   end of a file, sooner or later) or not finding something in
   a container;
- the returned value allows "naturally" for a special value
   which means "not found", "finished" like NULL or the superior
   alternative end() of a container;

Conversely, you use exceptions when the error condition is
really unexpected, rare (exceptions are very efficient if you
do not throw them and very inefficient when thrown, generally)
or you need to provide extra information in the error case (which
is very handy in debugging but useless overhead otherwise).

The killer argument for exceptions, in my view, is when the
caller of your function would have no clue as to what to do with
the returned error code except passing it back up to its own
caller and so on ... if the error is generated deep in the call
chain but handled (you do something beyond possibly logging it
and passing it back) up in the call chain, this is a case for
exceptions. A final case for exceptions is when writing library
or otherwise modular code: the library has no idea how it got in
the situation so it throws an exception and hopes the caller can
make good use of it.

If you have to change the function to return an enum and provide
the result through other means, e.g. a non-const reference
parameter, this might suggest using exceptions instead.

Davide Bolcioni
-- 
Paranoia is an afterthought.






More information about the tuxCPProgramming mailing list