The Right Approach to Exceptions

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Feb 20 08:41:13 PST 2012


On 2/20/12 10:31 AM, Sean Kelly wrote:
> On Feb 20, 2012, at 7:49 AM, Andrei Alexandrescu<SeeWebsiteForEmail at erdani.org>  wrote:
>>
>> Also, I think we can do better than defining the boilerplate constructor (see e.g. https://github.com/D-Programming-Language/phobos/pull/439). It's just a function. Consider:
>>
>> // this goes in the stdlib
>> void raise(ConcreteException)(string message, Throwable t = null, string f = __FILE__, size_t l = __LINE__)
>> {
>>   auto r = new ConcreteException;
>>   r.message = message;
>>   r.file = f;
>>   r.line = l;
>>   r.next = t;
>>   throw r;
>> }
>>
>> class AcmeException : Exception {}
>>
>> Now whenever you want to raise AcmeException, you say raise!AcmeException("message"). Also, raise may accept additional data that fills the Variant[string]. That makes exception definitions one-liners.
>
> What is gained here over the current approach:
>
> throw new AcmeException("message");
>
> Just eliminate the need for the ctor definition in the exception class?

Also possibly the definition of other constructors that set state. It's 
simple factorization.

Andrei


More information about the Digitalmars-d mailing list