On exceptions, errors, and contract violations

Sean Kelly via Digitalmars-d digitalmars-d at puremagic.com
Wed Oct 29 08:48:53 PDT 2014


On Wednesday, 29 October 2014 at 13:28:28 UTC, Bruno Medeiros 
wrote:
>
> Even if we could correctly differentiate between precondition 
> failures and postcondition ones, what would that gives us of 
> use?

It would give us an idea of where to look for the bug.  Also, it 
provides the option of discretionally reacting differently to 
each.


> I think in practice when some code hits an error in some 
> component that it uses, knowing whether it is a precondition 
> failure (bug in the code using the component), or a 
> postcondition (bug in the used component itself), it may 
> actually not tell us much about how much of the program has 
> been affected, ie, which fault domain is broken.

Yes, it may not.  This is really an artifact of the function 
being called.  I don't think any universal rules can be applied 
to pre vs. postcondition failures, but this at least gives the 
programmer the option of distinguishing between them for the 
cases where something can be done.  Though if we have something 
like this:

void f1() in { /* passes */ } body { f2(); }
void f2() in { throw new PreconditionFailure; } body { ... }

Then things get a bit muddied.  The bug here is really in the 
body of f1(), but the caller has no way of knowing that.  We 
could probably do something to indicate that this had occurred, 
but it's probably overcomplicating things.


> I think the default behavior should be simply the clean throw 
> of an Exception when an assertion fails. If there is a 
> performance issue with this, and we want to crash the program 
> immediately when an assertion fails, then that should be an 
> option too. However this behavior should be configurable per 
> library/component, not globally for the whole program, that is 
> too coarse. Also, it should be configurable *in the code* 
> itself, not at compile time. For some components it should even 
> be possible to use the component with hard-stop assertion 
> failure behavior in some places in the program, and with clean 
> exceptions in other places of the *same program*.

This is definitely possible, since the assert handler can be 
overridden, though it will not interact well with nothrow.


More information about the Digitalmars-d mailing list