Re: Assertion vs Exception Handling
Ian Collins <ian-news@hotmail.com> wrote:
On 03/15/10 07:51 AM, Daniel T. wrote:
Exceptions are for errors, that's what they were designed for. If
your program can handle some particular condition and continue
normal execution, how is that condition an error? The answer is, it
isn't.
Nonsense. Just because an error condition can't be handled locally,
doesn't mean it can't be correctly handled elsewhere.
"Something that can't be handled locally" seems to be a rather broad
definition of "error." Much too broad for me?
For example if an object fails to construct because a user specifies
an absent file, should the error be handled in the constructor, or
passed to a higher layer?
I subscribe to the same guidelines that Stroustrup outlines in his book:
Exception handling is a less structured mechanism than local control
structures such as if and for and is often less efficient when an
exception is actually thrown. Therefore, exceptions should be used
only where the more traditional control structures are inelegant or
impossible to use.
...
[Using exceptions as alternate returns] can easily be overused and
lead to obscure code. Whenever reasonable, one should stick to the
"exception handling is error handling" view. When this is done, code
is clearly separated into two categories: ordinary code and
error-handling code. This makes code more comprehensible. ("The C++
Programming Language" section 14.5)
Dealing with bad user input is quite ordinary as I see it.
As Stroustrup says though, the real world is messy and sometimes our
code reflects that. Messy code should not be our goal though.
As for your example, a function that opens a file should have the same
basic error conditions as a find function. In other words, it should
throw an exception only if "object" not found is an *error*. You may ask
how is the function supposed to know if "not found" is an error? The
answer is that if "not found" is not an error, and the function treats
it as such, then the caller should not use the function to do the job.
All this is IMHO of course, we were asked to provide guidelines and this
is the one I use.
I would never write a constructor in such a way that it must
successfully open a file in order to succeed, unless failure to open the
file means that the function creating the object cannot succeed, and on
up the chain.
If your code is littered with empty catch blocks especially, then
something is quite wrong with it as far as I'm concerned.