The Right Approach to Exceptions

Nick Sabalausky a at a.a
Mon Feb 20 12:17:44 PST 2012


"foobar" <foo at bar.com> wrote in message 
news:uphvtoqkvtshnzlqoaus at forum.dlang.org...
>
> I meant -
> what's the benefit of:
> throw createEx!AcmeException("....");
> vs.
> throw new AcmeException("....");
>

Fixed.

> As far as I can see, the former has no benefits over the simpler latter 
> option.
>

The benefit is that you don't have to create any boilerplate ctors in the 
definition of AcmeException.

*However*, I think that:

1. That's an insufficient improvement to justify breaking the ultra-common 
"throw new NameOfException(args)" idiom.

2. The solution fails to cover the *entire* scope of the *real* problem: 
Classes that need to write boilerplate ctors which merely forward to the 
base class's ctors.  This issue is *not* limited to Exceptions, but Andrei's 
proposes solution *only* covers the case with Exceptions.

A better solution has already been proposed:

    class AcmeException : Exception
    {
        mixin inheritCtors!();  // Actual name open for bikeshedding
    }

Now, yes, this *is* admittedly more boilerplate than:

    class AcmeException : Exception {}

However, it's superior overall, because:

1. The solution is *contained* to the author of the exception's class. It's 
*not* a solution that leeks out and infects user code.

2. It solves the *whole* problem in the general case, not just for 
Exceptions.

And you know what? Even if it's still deemed too much bolierplate, we can 
still just do this:

    mixin( createInheritedClass("AcmeException", "Exception") );

Or maybe this:

    // Second param is optional.
    // Not sure if this can be a template mixin or has to be string mixin.
    mixin createException!("AcmeException", "Exception");




More information about the Digitalmars-d mailing list