[LC++]functions return error nums: good practice?
db_linuxcpp at yahoo.it
Thu Nov 7 05:59:01 UTC 2002
Dr Mark H Phillips wrote:
> 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.
How do you plan to return the actual result then ?
> 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.
Since the function has a natural result type (which is not the
error code) and it seems that you're writing a function for
which the error handling strategy is not clear in your mind
yet, I would say that exceptions are still the superior choice,
in your case using something like domain_error or invalid_argument.
The key point in my mind is: upon seeing one of the special
"failure" values, is it the caller supposedly able to act upon
it in some meaningful manner, is it likely that it will have
to pass the bucket up the call chain or you have no idea yet ?
Only the first case would suggest a "failure" value.
> 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.
This is a burden for the normal case, when your function
does return a value.
> What are the pros and cons. Is there a better approach
> I haven't thought of yet?
Paranoia is a survival asset.
More information about the tuxCPProgramming