The Right Approach to Exceptions

Jonathan M Davis jmdavisProg at gmx.com
Thu Feb 23 02:57:43 PST 2012


On Wednesday, February 22, 2012 22:33:47 Jim Hewes wrote:
> On 2/21/2012 2:29 PM, Ali Çehreli wrote:
> > On 02/18/2012 09:09 PM, Jim Hewes wrote:
> >  > I think of exception handling as tied to contract programming.
> > 
> > I think your use of the word 'contract' is colliding with the contract
> > programming feature. What you describe later does not match with the
> > contract programming and I guess is the reason why Andrei is pointing
> > out two chapters from TDPL.
> > 
> > I will reread those chapters later today but I think Andrei is referring
> > to the distinction between assert() and std.exception.enforce().
> 
> Thanks. I assume the objection is about the bad parameters. In design by
> contract, a function should not be checking the input, correct? It
> assumes it's correct. But I was mostly thinking of the case when the
> functions are more of a public API and you can't trust the input. I did
> mention using assert for internal functions. But I guess if you are
> strict, you should never check input. I just shouldn't mention design by
> contract at all then. :)

In DbC, you use assertions to verify arguments, because it's up to the caller 
to ensure that the arguments are valid - otherwise it's breaking the contract. 
So, in release mode, there are no checks, and in non-release mode, your 
program gets killed if the contract is violated. It's considered a bug in the 
code if bad arguments are passed to the function.

In defensive programming, however, you use exceptions, which is much safer, 
because the function will never actually execute with bad arguments, but it's 
slower, because it's always checking, whereas assertions are compiled out in 
release mode. Also, it's not necessarily a bug when you pass an invalid 
argument to a function using defensive programming, because throwing an 
failure is part of its normal behavior (and won't be compiled out in release 
mode) and is recoverable, unlike an AssertError. Rather, the function is 
merely informing the caller that it was given bad arguments and lets the 
caller sort it out.

DbC tends to work better with internal stuff where you control both the caller 
and the callee, whereas defensive programming works better with public APIs. 
But regardless, which is best to use depends on the situtation and what you're 
goals are.

- Jonathan M Davis


More information about the Digitalmars-d mailing list