The Right Approach to Exceptions

Juan Manuel Cabo juanmanuel.cabo at
Mon Feb 20 13:06:11 PST 2012

I like one golden rule that I have:

 "You should only create a new exception type, if it makes sense to write
  a  catch(MyNewShinyType ex){}  "

other reasons for creating a new exception class I don't consider them valid
(but that's just me!).
This is because, exception types (in my head) are only a way to distinguish
whether to select them or let them go when I write a catch(), and to
help the catch recover.  Now, if I can't distinguish the *what* of the error,
I cannot recover well. The *cause* of the error goes inside the exception
object, not encoded in the type. Other details of the error go inside of
the exception object, not encoded in the type name.

So all I care about is the *what* of the error, so that it will fall in
the correct catch statement. Other criteria obscures that.

The Variant[string] helps keep the hierarchy clean. The hierachy should
tell the *what* of the error so that I can pick one when writing a catch block.


On 02/20/2012 05:51 PM, Jonathan M Davis wrote:
> 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