The Right Approach to Exceptions
Jonathan M Davis
jmdavisProg at gmx.com
Fri Feb 24 16:37:03 PST 2012
On Friday, February 24, 2012 16:18:59 H. S. Teoh wrote:
> On Fri, Feb 24, 2012 at 06:48:47PM -0500, Jonathan M Davis wrote:
> > 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.
You do run into the who rethrowing issue with that though, if you catch the
wrong type. It also can force you to combine disparate catch blocks, since you
caught the common type, and you're forced to use if-else statements to
separate out the various cases instead of letting catch take care of it. All
in all, it would just be _way_ cleaner to have a way to give a list of
exception types that you want that catch to catch.
Also, I think that having a syntax for simply giving a list of exceptions that
an exception block catches is plenty without needing the whole condition
thing. The condition thing just seems like overkill. But maybe someone has a
valid use case where giving a specific list of exceptions doesn't cut it.
> 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. :)
Indeed. What we need is a setup which enables (and hopefully encourages)
people to do the right thing. We can't stop people from being stupid.
For instance, much as Java generally tries to protect you from your own
stupidity, the fact that it has very good exception hierarchy doesn't stop
people (and in some cases the developers of its standard library) from doing
stupid things with exceptions. And D, which tries to protect you without
preventing you from being stupid (unlike Java, which generally tries to
prevent you from doing something stupid), certainly isn't going to stop you
from being stupid.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list