Re: Exceptions, Go to Hell!
"joe" <jc1996@att.net> wrote:
Daniel T. wrote:
... The question was "what do you call those things that return
codes and C++ exceptions are used for?" My answer is, "precondition
violations."
Oh? Just that? What about postconditions and invariants?
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.
I was alluding that there may be more (at least I'm not ready to place
a seal on just those things as constituting all errors).
Exceptions should not be (and in fact, cannot be) used for "all errors,"
unless you define "error" as a precondition violation.
A definition of error that is "failure of or failure to achieve
preconditions, postconditions, invariants" seems much less broad (and
therefor less correct) than "anything that will cause a function to
fail". Of course, "bugs" are not included in the latter.
To me, your two quotes above are equivalent, so neither is less correct
or less broad than the other.