The Right Approach to Exceptions

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Feb 20 10:02:04 PST 2012


On Mon, Feb 20, 2012 at 06:55:13PM +0100, deadalnix wrote:
> Le 20/02/2012 18:11, Andrei Alexandrescu a écrit :
[...]
> >That extra processing must format the message given the information
> >passed by the exception. _Definitely_ it doesn't make sense to put
> >the formatting processing in the exception. That's why shipping the
> >information outside the exception in a generic format is necessary,
> >hence the Variant[string].
> >
> >
> >Andrei
> 
> And so variant is the way to go ?
> 
> Clearly, this is a very strong arguement in favor of typed Exception,
> that provide usefull information about what went wrong.  This is a
> safe approach.
> 
> Because this Variant stuff is going to require massive ducktyping of
> Exceptions, with all possible errors involved. The keys in the
> Variant[string] will depend on the Exception the dev is facing. This
> should be avoided and should warn us about the requirement of typed
> Exceptions.

Exactly! Just because you use a Variant doesn't magically free you from
needing to know what exactly is that exception that you caught in the
first place. To make any sense of what's stored in the Variant, you
still have to know what is the exception type, and based on the type
interpret the Variant. So you end up with:

	catch(Exception e) {
		switch(e.type) {
			case BlahException:
				handleBlahException(e.data.blah_info);
				break;
			case BlehException:
				handleBlehException(e.data.bleh_info);
				break;
			case BluhException:
				handleBluhException(e.data.bluh_info);
				break;
			...
		}
	}

which is exactly the kind of ugliness that class hierarchies were
invented to solve.


T

-- 
ASCII stupid question, getty stupid ANSI.


More information about the Digitalmars-d mailing list