The Right Approach to Exceptions

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Feb 20 18:36:16 PST 2012


On 2/20/12 7:07 PM, Jonathan M Davis wrote:
> On Monday, February 20, 2012 18:38:08 Andrei Alexandrescu wrote:
>> On 2/20/12 6:25 PM, H. S. Teoh wrote:
>>> This is what I mean by not being able to depend on whether some data is
>>> there. Ultimately, to do anything useful with the info in the object,
>>> you need to know what's there.
>>
>> No. You do realize you are positioning yourself straight against every
>> OO principle there is? The entire OO world is predicated on the
>> assumption you _can_ do useful stuff with an object WITHOUT knowing
>> what's there.
>
> Exceptions aren't very OO really. Aside from getting a string out of them, you
> generally don't have any polymorphism involved, and even with the string,
> there's a good chance that you don't. For instance, the message field which
> toString uses to generate its string is passed as an argument to Exception's
> constructor.

(Cloning and comparison are also essential polymorphic methods to 
implement.) But then again the view "exceptions are wildebeests" is 
coming straight from inside the box. We want to improve on that.

> With exceptions, it's the types that matter. It's not a case of changing
> behavior based on implementation. With OO, you try _not_ to care about what
> the type is. With exceptions, on the other hand, you care a great deal. It's
> inverted from OO. Exceptions hold data but not much behavior. The behavior
> goes in the catch blocks.
>
> If we had a construct which allowed inheritance but not polymorphism (which we
> don't, since for better or wors, inheritance is conflated with polymorphism in
> D), then that would make a lot of sense for exceptions.

I don't think inheritance without subtyping would help any. C++ has it 
(non-public inheritance) but that didn't improve exceptions one bit.

> It doesn't really hurt us that exceptions have polymorphism, but it doesn't
> generally help them do their job at all. If you're going to do anything beyond
> simply print an error message, you need to know what the exception type is and
> what data it has. And that's not OO at all.

Or you need to implement a key-value interface that allows printing of 
an elaborate error message.


Andrei


More information about the Digitalmars-d mailing list