Re: error handling best practices
On Aug 23, 3:46 am, Phlip <phlip2...@gmail.com> wrote:
On Aug 22, 7:31 pm, MaksimKneller <mknel...@gmail.com> wrote:
Under which circumstances is it best to report/record errors via:
- exceptions
- returning an enum indicating success/fail
- just writing the error to a log
Yes.
There are even a few rare cases where the best solution is
simply to memorize the error in the interal state of an object,
for later testing, a la iostream. (And when I say rare, I mean
very rare.)
And of course, there's also the possibility of aborting with an
error message.
So far I can think of 'just writing to a log' as preferable when the
success of a program isn't affected by the error (execution can
continue) but the error is still worthy of note.
And your unit tests should be able to simulate the situation, at the
low level.
(You do _have_ unit tests, don't you?)
A program module should have a boundary and inner logic. The
boundary is where it accepts inputs from the outside "world"
- either other modules, or data, or users. The boundary
filters out bad inputs, converts commands into OO types with
the corresponding behaviors, and then calls into the inner
logic.
If the calling function violates any part of the contract
(typically pre-conditions), then the only correct handling is an
assertion failure---abort with an error message. The program is
broken.
(For the rest, I pretty much agree with you.)
--
James Kanze