The Right Approach to Exceptions

Jonathan M Davis jmdavisProg at gmx.com
Mon Feb 20 11:27:11 PST 2012


On Monday, February 20, 2012 11:15:08 H. S. Teoh wrote:
> On Mon, Feb 20, 2012 at 01:52:15PM -0500, Jonathan M Davis wrote:
> [...]
> 
> > So, instead of
> > 
> > catch(SpecificException1 e)
> > {
> > 
> > //use fields specific to this exception to do whatever you need to do
> > 
> > }
> > catch(SpecificException2 e)
> > {
> > 
> > //use fields specific to this exception to do whatever you need to do
> > 
> > }
> > catch(GenericException e)
> > {
> > 
> > //handle the generic exception as best you can given the lack of
> > //a specific one
> > 
> > }
> > 
> > you end up with something effectively along the lines of
> > 
> > catch(GenericException e)
> > {
> > 
> > if(/* e is SpecificException1 */)
> > {
> > //use fields specific to this exception to do whatever you need to do
> > }
> > else if(/* e is SpecificException2 */)
> > {
> > //use fields specific to this exception to do whatever you need to do
> > }
> > else
> > {
> > //handle the generic exception as best you can given the lack of
> > //a specific one
> > }
> > 
> > }
> 
> [...]
> 
> I think what Andrei wants to do is more along these lines:
> 
> catch(Exception e) {
> writeln(formatLocaleString(e.fmt, e.data));
> }
> 
> I think there's some merit to this idea. However, I'm still unsure about
> storing stuff in a Variant.

Except that if you're not printing out the message, if all of the data is in 
e.data as a variant, then you _do_ end up with code like I gave. The variant 
is a bad idea for anything trying to actually handle the exception rather than 
just print out a message.

> That's why I proposed to use runtime reflection to scan the exception
> object for applicable fields. Then you get the best of both worlds: the
> message formatter doesn't need to know what the fields are, and you get
> full compile-time type checking for catching code that directly accesses
> the fields.

That would certainly be better.

- Jonathan M Davis


More information about the Digitalmars-d mailing list