J
Joshua Maurice
When a library writer finds that a postcondition or invariant failure
has occurred in his code, it should be fixed. When a precondition
failure occurs in his code, he should throw an exception, there is no
way for him to "fix" it.
From what I see, the bigest question new programmers have about the
exception mechanism is about when to use it. They are told vague
generalities but not given anything concrete (they are told to use them
for "errors" and "exceptional situations".) I'm trying to clear out some
of the vagueness. As Stroustrup put it:
... the author of a library can detect run-time errors but does not
in general have any idea what to do about them. The user of a library
may know how to cope with such errors but cannot detect them or
else they would have been handled in the user¹s code and not left for
the library to find. The notion of an exception is provided to help
deal with such problems.
What Stroustrup is describing above are precondition violations.
Exceptions should not be (and in fact, cannot be) used for "all errors,"
unless you define "error" as a precondition violation.
To me, your two quotes above are equivalent, so neither is less correct
or less broad than the other.
I've been following this thread with a sense of dread, mostly because
I've seen this pop up several times and the same rehashed arguments
are given. Counter example to your claims:
1- Library should throw on every pre-condition violation. Sometimes
this is overly expensive or impractical to calculate. My favorite
example is the non-recursive mutex. Under "release mode" options, we
want it to be incredibly fast, and it is quite a noticable hit on some
systems to make it track this. Better yet, the system could detect
some deadlock conditions, but that would be incredibly expensive, so
again we do not want such deadlock detection turned on under "release
mode" options.
2- Libraries should not throw on post-condition violations. So, what
should we do when std::new fails to allocate memory? Or when a file
flush fails due to whatever reason (like the USB stick being
removed)?
What you say doesn't make sense unless you weaken all pre and post
conditions to drivel, such as weakening operator new to "Maybe it
allocates memory, maybe it doesn't".
I argue that "it depends" and I have yet to find a better succinct
rule. More specifically:
If you want fast code, then don't use exceptions on the code which is
required to be fast. If an error condition is not part of the fast
path, the set of use cases determined to have value, then exception
use may be warranted.
As more of a matter of an educated guess, if you want more
maintainable code, then if you have an error condition which is
unlikely to be handled at the caller, and is instead likely to be
handled much farther up the call stack, then use an exception.