The Right Approach to Exceptions

H. S. Teoh hsteoh at
Fri Feb 24 16:18:59 PST 2012

On Fri, Feb 24, 2012 at 06:48:47PM -0500, Jonathan M Davis wrote:
> However, Java does have a great exception hierarchy, much of which is
> standard. And that's a lot better than having only a handful of
> unrelated exceptions, let alone having all exceptions be specific to a
> module like we do now.
> So, we really have 2 problems here:
> 1. Phobos doesn't have a proper exception hierarchy. Its exceptions
> need to be better organized according to the problem that they
> indicate rather than by module.


> 2. There are something things that can be done to Exception and how
> exceptions work in D to help resolve issues related to wanting to
> catch and handle exceptions without having to catch all exceptions
> that match their common base type or otherwise have to duplicate code
> among catch blocks.
> The two proposals that seem best for this are
> 1. Being able to annotate catch blocks in some manner to enable them
> to catch multiple, specific exceptions - either by using some kind of
> condition
> catch(Ex1 e) if(condition)

Even though I was (one of) the one(s) who proposed this syntax, I think
a better syntax would be something like:

	catch(Ex1 e: condition)

but that's just bikeshedding.

> which, as you point out, would have to be done at runtime, or by doing
> something similar to what Java 7 is doing and make it so that multiple
> exceptions can be caught with the same block
> catch(Ex1, Ex2, Ex3 e)
> and e ends up being the most derived type that is common to them.

This can also be done by catch conditions by using is-expressions or
derived class casts, though it would be more verbose. We may not need to
implement both.

> So, if we better organize Phobos' exceptions, implement a multi-catch
> feature, and implement Andrei's Variant[string], then Phobos'
> exceptions will work far better (and by far more reusable), and some
> of the greater shortcomings of D's exceptions themselves should be
> mitigated, if not eliminated.


> Naturally, that still won't stop people from doing stupid things with
> exceptions in their own code (like throwing on EOF), but we'll have a
> good setup for those who use exceptions properly, and we should be
> able to avoid putting stupid uses of exceptions in Phobos, simply
> because the code is open and peer-reviewed, and I think that most of
> the people around here agree that using exceptions for stuff like EOF
> is stupid.

I don't think D's job is to stop people from doing stupid things.
Otherwise we might as well go back to Pascal or something. :)


For every argument for something, there is always an equal and opposite
argument against it. Debates don't give answers, only wounded or
inflated egos.

More information about the Digitalmars-d mailing list