The Right Approach to Exceptions

Jonathan M Davis jmdavisProg at gmx.com
Mon Feb 20 12:51:20 PST 2012


On Monday, February 20, 2012 17:31:28 Juan Manuel Cabo wrote:
> > ...
> > Sure. Again, this is not advocating replacement of exception hierarchies
> > with tables! ...
> > 
> > Andrei
> 
> I think that the case of rethrowing an exception with added detail is the
> worst enemy of clean Exception hierarchies.
> The idea of Variant[string] remedies that case without creating a new
> exception class just for the added fields. If that case is solved, then the
> tipical need for creating new exception types that don't really aid
> selecting them for catching and recovery is solved too.

Having derived exceptions with additional information is a _huge_ boon, and I 
contend that it's vasty better with variant, which would be highly error 
prone, because it's not properly statically checked. Changes to what's put in 
the variant could kill code at runtime - code which by its very definiton is 
not supposed to be the normal code path, so you're less likely to actually run 
into the problem before you ship your product. Whereas with the information in 
actual member variables, if they get changed, you get a compilation error, and 
you know that you have to fix your code.

Rethrowing is a separate issue. And in many cases, the correct thing to do is 
to chain exceptions. You catch one, do something with it, and then you throw a 
new one which took the first one as an argument. Then you get both. That 
functionality is already built into Exception.

- Jonathan M Davis


More information about the Digitalmars-d mailing list