The Right Approach to Exceptions

Jonathan M Davis jmdavisProg at
Tue Feb 21 11:17:50 PST 2012

On Tuesday, February 21, 2012 10:57:20 Andrei Alexandrescu wrote:
> On 2/21/12 10:50 AM, Juan Manuel Cabo wrote:
> > I thought that an alternative to Variant[string] would be to have some
> > virtual functions overrideable (getExceptionData(string dataName) or
> > something). but they would all have to return Object or Variant, so it's
> > the same thing.
> Exactly. By and large, I think in the fire of the debate too many people
> in this thread have forgotten to apply a simple OO design principle:
> push policy up and implementation down. Any good primitive pushed up the
> exception hierarchy is a huge win, and any design that advocates
> reliance on concrete types is admitting defeat.

Exceptions do _not_ lend themselves to polymorphism. Having them in a type 
hierarchy is useful. It allows you to deal with them at varying levels of 
abstractions. But ultimately, you deal with the concrete types, _not_ an 
abstract interface. In that sense, they're not OO _at all_.

Adding a Variant[string] property to allow adding on additional information if 
a particular application finds it useful may be a good thing to do. But it 
should be an _add on_, not the core design. Aside from printing strings, 
trying to deal with exceptions generically just does not make sense. At best, 
you might care about a common exception rather than a more specific one in 
particular case (e.g. catching IOException rather than FileException). But if 
you're trying to actually handle the exception in any real way rather than 
just print out a message, you need the concrete type, not an abstract 

I think that you're pushing the OO angle too hard onto exceptions. They're not 
completely separated from it, but they really aren't classic OO and shouldn't 
be treated as such. If anything, they're inverted, because you frequently try 
and deal with as concrete a type as possible rather than as abstract a type as 
possible. The hierarchy aspect is really the only truly OO aspect of 
exceptions IMHO. For the most part, polymorphism just doesn't enter into it. 
And Exception really already declares the few functions where it does.

- Jonathan M Davis

More information about the Digitalmars-d mailing list