The Right Approach to Exceptions

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Feb 21 13:15:19 PST 2012


On 2/21/12 2:47 PM, H. S. Teoh wrote:
> On Tue, Feb 21, 2012 at 09:32:35PM +0100, deadalnix wrote:
> [...]
>> So it doesn't help. Dulb subclasses of Exceptions are done mostly to
>> be able to catch them. To avoid useless subclasses, we need a more
>> precise way to catch Exception than the type only.
> [...]
>
> This is a good point.
>
> Has anybody even considered, *why* does catch match by type? Is there a
> good reason for that? Or is it just inherited from the rah rah days of
> OOP where "everything is an object", so since exception is part of
> everything, exception is an object, therefore we can just catch by
> object type?

I think a reason is that exceptions should be able to transport an 
arbitrary amount of information. That means heterogeneous types at 
least. Then, as you discussed in the beginning of the thread, placing 
types in a hierarchy allows client code to catch several exceptions 
sharing a common super type, theory that was well understood.

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.

>> From all the heated debate in this thread, it's clear that exceptions
> don't map very well to a class hierarchy, at least not without points of
> contention and what amounts to workarounds and hacks.
>
> 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.


Andrei


More information about the Digitalmars-d mailing list