[LC++]functions return error nums: good practice?

Dr Mark H Phillips mark at austrics.com.au
Wed Nov 6 14:00:01 UTC 2002


Suppose I have a function which, for certain combinations
of input, will be unable to compute a sensible result.  One
way of dealing with this is to have the function return an
int, which will be 0 if everything is okay, and a non-zero
if it isn't.  The particular non-zero chosen will indicate
the type of error which was encounted.  The calling routine
can then choose to handle the error however it wishes based
on the error number it receives.  You can have constants
(either macro or const constants, or even enums) to give
a name to each of the error possibilities.

I believe this is a fairly common "C" way of doing things.
My question: is this a good way to do things in C++?

The alternatives I can think of are:

1. Use exceptions.  Probably not appropriate in this context
because "cannot compute with this input" is a valid part of 
normal operation.

2. Return an error object rather than an int.  This object
might contain information like a standard error message
string associated with the error.  Whereas with the int
error, you might have an array of error messages stored
somewhere else.  I don't know which one is better.

What are the pros and cons.  Is there a better approach
I haven't thought of yet?

Also, if I do go the int error route, there are two ways to
go about this:

1. Have a single list of ints for errors of all functions.

2. Have a separate list of error ints for each different
function returning an error int.  Ie the same int could
represent a different error depending on what function it
was produced by.

Which is best?



Dr Mark H Phillips
Research Analyst (Mathematician)

AUSTRICS - smarter scheduling solutions - www.austrics.com

Level 2, 50 Pirie Street, Adelaide SA 5000, Australia
Phone +61 8 8226 9850
Fax   +61 8 8231 4821
Email mark at austrics.com.au

More information about the tuxCPProgramming mailing list