The Right Approach to Exceptions

Jonathan M Davis jmdavisProg at gmx.com
Fri Feb 24 10:47:00 PST 2012


On Friday, February 24, 2012 08:27:44 H. S. Teoh wrote:
> On Fri, Feb 24, 2012 at 07:57:13AM -0800, H. S. Teoh wrote:
> > > On Thursday, February 23, 2012 15:18:27 H. S. Teoh wrote:
> > > > In my book, a linked library shares equal status with the "main
> > > > program", therefore the definition of "user input" still sits at
> > > > the internal-to-program and external boundary.
> 
> [...]
> 
> > I wasn't trying to say that library code should always use DbC and
> > application code should always use defensive programming. I'm saying
> > that if it makes sense for a function to use DbC (or vice versa) then
> > it should use DbC regardless of whether it's in a library or not.
> 
> [...]
> 
> Argh, I just realized that my first post was so poorly worded it made no
> sense at all. My second post was what I meant to say. :)
> 
> What I was trying to express in the first post was that "user input"
> comes from a source external to the program, whether from a user typing
> at the keyboard, or from a file or network resource, and this data
> traverses program code paths until eventually they are converted into
> the internal form the program uses for further processing. Input
> sanitization should be done along this code path until the input is
> processed into program-internal form, at which point, DbC begins to take
> effect, the assumption being that after preprocessing by the input
> sanitization code, all data should be valid, and if not, it's a failure
> of the input processing code and represents a logic flaw in the program,
> therefore an assertion should be thrown.

Yes. In general, that's the core difference between assertions and exceptions. 
If an assertion fails, it's a bug in the code, whereas if an exception is 
thrown, then it may or may not be caused by a program bug (and is frequently 
caused by interacting with I/O - be it directly or indirectly).

But that does require a judgement call sometimes as to which approach is 
better in a particular situation, and if you're being utterly paranoid (which 
some programs probably need to be but most don't), then you could end up using 
exceptions where you'd normally use assertions simply because you want to 
_guarantee_ that the check is always done. But hopefully, that sort of thing 
would be kept to a minimum.

Regarldess, at the core, assertions are for verifying program correctness, and 
exceptions are for reporting error conditions caused by bad stuff happening 
during the normal operation of the program.

- Jonathan M Davis


More information about the Digitalmars-d mailing list