Re: Error codes vs. exceptions
The ability to make such a determination is extremely rare, including
for invalid input. Exceptions should be the normal response to
invalid input to a function, including to invalid input supplied by
the outside world.
That opens slippery slope for mixing program logic errors with
factors outside our control.
So does this mean that we should prefer _error codes_, not exceptions, and
reserve exceptions only for the _rare_ "environmental" error? Now I'm even
confused. How do you handle a failing constructor?
No, it just means that for the case where the program detects it is in
*unexpected* state, you don't throw neither return a code, but halt the
program right then and there, avoiding to mess up even more.
Error handling -- by whatever means -- is to handle expected conditions.
So there is a fundamental difference.
Say you have a std::vector and use it by index, you keep the index in the
[0, size()-1) range, always. Your code will never generate illegal index to
call op. If somewhere the supposed index is coming from some unknown
source, like read from a file or socket, you first do the gating. That will
either prevent getting to the indexing operation, or reset the incorrect
input to usable range.
Correct index is PRECONDITION of op, that is properly specified. You
violate that and get undefined behavior. So you just don't get there. ;-)
And it applies to anything you design. Including ctors. What you consider
precondition, you just expect. If having preconditions met the ctor still
can fail, you have limited options: you either throw or construct to some
special state. Id you're okay with something like 'empty' or 'default', it
may fly. If you must set an 'invalid' state, such class will be major PITA