Re: Error codes vs. exceptions
I've heard about this, and wonder when is it right to use codes, and
when to use exceptions for reporting errors?
Simple guide is that you use return code if the immediate caller is supposed
to care about the failure details and act. While throw is for long-range
communication. Not surprizingly for some functions both make sense.
I've heard various stuff,
such as that exceptions should only be used to indicate "exceptional"
conditions. Yet what does that mean? I've heard that, e.g. a user
inputting invalid input should not be considered "exceptional", but
something like running out of memory should be.
Makes sense.
Does this mean that if
we have a program, and we have a "parse()" function that parses a
string input by the user, that this function should return an error
code on parse failure, instead of throwing an exception? Yet we'll
probably also come across places where it's good to use an exception,
in the same program! Which means we get into _mixing error codes and
exceptions_. And what's the best way to do that?
Look for antipatterns.
If you see abundance of try blocks, especially catch after a single call,
the function would be better off with return code.
If you see return-code-football happening, like a row of
if ( (ret = Act()) < 0)
return ret;
you'd be better off throwing, and a catch where actual handling happens.
Certainly this applies to healthy, C++-style code, where objects take care
of themselves (see RAII), and no explicit management code is needed. If you
see free/delete/close... actions in the catch blocks and after those ifs,
fix that first.
Also, how exactly does one go about determining what is and is not
"exceptional"?
You issue a command and expect it to succeed under normal working
conditions. I.e. I expect that there's enough memory to complete the task,
that there's enough space on FS to write, TCP connection delivers, the valid
database operation carries out, I can open the files the program created,
or are there as part of the install.
If any of those fail, it's exception.
OTOH raw input form a user/outside world can be anything, so first it must
be checked/sanitized. Failure is properly expected.
However the decision is a practical matter. you balance good-looking code
and consider runtime penalties. Don't sweat on cases where you have no clear
pick.
Two examples were mentioned of things exceptional and
non-exceptional, but what about something else, like say in a game,
where you have a grid representing a game level, and a request for a
tile of the level is made with a coordinate that is off the map (like
a 64x64 map and something requests a tile at (100, 100).).
Depends on what is asking. If your program code that should have obey the
bounds, then it is a completely different field, that of assert() and
terminate() due to detected bug.
If it's input from outsude, then you shall gate it, and have behavior
defined in the design.
Would it be
OK for the function working on the tile to throw? Or should it give an
"out of range" error code? And as for that mixing: consider, e.g. C++
and probably many other languages: a function has a single definite
return type. Suppose our grid had a function that extracts an
attribute from a cell. What to do when there's an out-of-bounds
request?
That is up to you to define. If you specify the bounds as precondition, then
you may leave the behavior undefined. (Or you may define it to something,
but it helps little outside a testing environment).
Throw exception? See, what I've currently been doing, and
it's probably silly, is to use exceptions when our function needs to
return a value, and error codes when it could otherwise return "void".
Certainly the function is hosed. :) exception looks like the easy way out.
But that holds only locally. If the caller thought the bounds were okay, and
turned out wrong, who shall handle the exception and how?
OTOH you can define the function as 'best-effort', and allow blind calls.
Definig the behavior as you like, including to throw or return some default
ot NULL object. (consider a sparse matrix with unlimited size, that holds
only values for cells explicitly set, and for anything else returns 0.)
This doesn't seem like a good idea. But what to do? Make every
function return an error code, using pointers to output variables to
store output, and only use exceptions for a rare few kinds of "system-
related" error? Yet one can hardly deny the niceness of being able to
say "x = f() + <foo>" (inside a "try" block, perhaps) instead of
if(f(&x) != SUCCESS)
{ // handle error }
x += foo;
:)
Exactly. The cheese of error handling is the HANDLING part, not emitting
the error via whatever means. Concentrate on that, and the rest will be
easy.
In a normal system that use exceptions the catch stes are pretty rare, and
most functions are exception-transparent.
The function that detects a problem condition is normally clueless on what
to do, and same goes for its immediate invoker... :)
Note how we can easily get LONG methods full of repeated code with
error codes (repeated error handlers to handle similar errors at
various function calls calling error-code-emitting functions, if one
wants to be more graceful than simply aborting with an error to the
next level up
This sounds quite fishy. You either handle the error or not -- there is
hardly place to be graceful.
(which complicates what error codes a function can
return, since it can return its own codes in addition to those
returned by the functions below it, and those may have functions below
THEM, and so on...).). And who likes duplicated code? eww. This seems
a disadvantage of error codes.
It is.
Or, and this is what I've been thinking of, use exceptions for every
error that the user does not have control over, like invalid input
strings. Would that be OK or excessive use of exceptions? And if we
are to mix error codes and exceptions, does this mean we should have
the lists of codes and exceptions correspond + a translator to
translate between the two?
Why you think they shall be connected? Just use everything for its own
benefit.