The Right Approach to Exceptions
H. S. Teoh
hsteoh at quickfur.ath.cx
Tue Feb 21 14:29:32 PST 2012
On Tue, Feb 21, 2012 at 03:15:19PM -0600, Andrei Alexandrescu wrote:
[...]
> A more debatable aspect of exceptions is the first-match rule in
> catch blocks. All of OOP goes with best match, except here. But then
> all code is together so the effect is small.
Does it make sense to make it best-match? Or is that too risky since
everyone expects it to be first-match?
[...]
> >So I'm going to throw (har har) this very crazy and wild idea out
> >there and let's see if it's viable:
> >
> >What if instead of catching by class, we catch by attribute matching?
> >So instead of writing:
> >
> > try { ... }
> > catch(SomeExceptionType e) { ... }
> > catch(SomeOtherExceptionType e) { ... }
> > catch(YetAnotherSillyException e) { ... }
> >
> >we write:
> >
> > try { ... }
> > catch(e: exists!e.filename&& e.failedOp is File.open) {
> > // something
> > }
> > catch(e: e.is_transient&& e.num_retries< 5) {
> > // something else
> > }
> > // And why should we even need an exception object in the first
> > // place?
> > catch(time()>= oldtime+5000) {
> > // This thing's been running for way too long, time to
> > // do something drastic
> > }
> >
> >Flamesuit on! ;-)
>
> The only problem I see here is ascribing e a type.
[...]
True, for this to work in its full generality would require duck-typing
(the catch block can use any property it tests for, regardless of type).
Which D doesn't have.
So it looks like we're back to catch conditions, that has come up a few
times in this thread:
try { ... }
catch(Exception e: e.is_transient && ... || ...) {
// or whatever the latest proposed syntax is, the idea
// is the same.
}
catch(Exception e: !e.is_transient && ...) {
// the previous block doesn't catch if conditions fail,
// so we can still get Exception here.
}
This does start to look like it might make sense to switch to best-match
instead of first-match for catch clauses.
T
--
Your inconsistency is the only consistent thing about you! -- KD
More information about the Digitalmars-d
mailing list