The Right Approach to Exceptions

foobar foo at bar.com
Mon Feb 20 14:24:20 PST 2012


On Monday, 20 February 2012 at 20:18:58 UTC, Nick Sabalausky 
wrote:
> "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.

Huh? <confused>

>
>> 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");

I completely agree with the above. Clearly Andrei's template 
solution here is insufficient and the bigger issue is of course 
the pollution of user code.

I just want to add to the above valid points one comment:
instead of the proposed inheritCtors D could e perhaps modified 
to make ctors more uniform with other methods. ctors could be 
automatically inherited if sub class does not define its own 
ctors and does not add new fields.

the above would simply become:

class AcmeException : Exception {} // inherits super ctors 
automatically



More information about the Digitalmars-d mailing list