Why exceptions for error handling is so important

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Thu Jan 15 13:26:40 PST 2015


On Thu, Jan 15, 2015 at 09:01:35PM +0000, via Digitalmars-d wrote:
> On Monday, 12 January 2015 at 20:53:04 UTC, Walter Bright wrote:
> >On 1/12/2015 10:06 AM, Tobias Müller wrote:
> >On Mon, Jan 12, 2015 at 05:22:26PM +0000, Adam D. Ruppe via Digitalmars-d
> >wrote:
> >>>Yeah, exceptions are supposed to be ... well, *exceptions*, rather
> >>>than the norm. :-) If you're using exceptions to do flow control,
> >>>you're doing something wrong.
> >>
> >>But what's exceptional for you is normal for me.
> >
> >It's not a subjective truth, it's an objective fact.
> >
> >If code is throwing exceptions as part of its normal operation, it is
> >designed wrong.
> 
> But what this means that exceptions should only ever be used for
> catching programming errors, some kind of "soft" assertions.

No, that's wrong. Programming errors are caught by assertions, not
exceptions.

Exceptions are used for handling unexpected *environmental*
circumstances, such as a file that should be there but isn't, a disk
that should be able to store data but happens to be full, a network
server you need to talk to that ought to be present but is down for some
reason, data received from a helper program that ought to have a certain
format but for whatever reason sent malformed output instead.


> It also means, that exceptions should only be thrown, but never be
> actually handled, because by handling it you would "admit" that it's
> actually normal operation.
> This is not what I call error *handling*.

Huh?! Handling unexpected circumstances is hardly "normal operations",
it's making the program deal gracefully with problem situations in the
environment that normally shouldn't occur. If the default server is
down, switch to a backup server. If a required file is missing, fall
back to a backup copy, or give up, file a log message, and clean up any
resources properly before exiting. Etc..

That doesn't change the fact that problem situations should not be the
norm -- if it is, then you're doing something wrong. A server shouldn't
be constantly down. A required file shouldn't be mysteriously missing
every other hour. Etc..

Unless, of course, the *purpose* of the program is specifically to deal
with problem situations -- in which case, you wouldn't be using
exceptions to indicate those situations, you'd treat them as "normal"
input instead. You wouldn't be using try/throw/catch, but normal
flow-control constructs.


T

-- 
It won't be covered in the book. The source code has to be useful for something, after all. -- Larry Wall


More information about the Digitalmars-d mailing list