The Right Approach to Exceptions
Mafi
mafi at example.org
Mon Feb 20 09:08:09 PST 2012
Am 20.02.2012 17:41, schrieb Andrei Alexandrescu:
> 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
If it's supposed to be simple factorization, then you should replace
"throw r" with "return r". Then the name of that function doesn't make
much sense anymore. But then you can better search for throw in user
code and the stack traces aren't obfuscated anymore.
throw createEx!AcmeException("....");
Mafi
More information about the Digitalmars-d
mailing list