The Right Approach to Exceptions

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 18 16:24:11 PST 2012


On Saturday, February 18, 2012 18:09:30 Andrei Alexandrescu wrote:
> Of course I can. They call it toString(). The code above pretty much
> proves my point with so much wonderful irony.

How?!! toString doesn't help _at all_. It just gives whatever getopt can come 
up with, not what's appropriate for your program. And right now, since there's 
no GetOptException, you just end up with a ConvException, so you don't even 
get a semi-decent toString. You have _no idea_ what flag had the error. The 
best that you can do is print out that _something_ went wrong, not _what_. And 
if you want to do fancier handling (_especially_ if you want recover from an 
exception rather than just print a message), you need _far_ more than 
toString. Maybe I want to look at the flag that you gave me which was invalid 
and then suggest what you might have meant. Without _at least_ knowing what 
the flag was that you used (which I can't do with the current getopt), I can't 
do that.

How could you do something even close to my example with getopt as it is now?

Perhaps getopt is not the best example, because it's likely to end up with you 
giving an error to the user regardless. But other exception handling wouldn't 
necessarily involve the user at all. The primary issue is giving the program 
the information that it needs to actually handle and potentially recover from 
the exception. A string doesn't do that. Giving the exception a specific type 
according to what went wrong and additional member variables with information 
on what went wrong _can_ do that.

What if something goes wrong when processing a file? Did something go wrong 
with the file operations or in processing the information? A FileException vs 
another exception type (e.g. UTFException or ParseException) would tell you 
that. And if you want to recover from the exception and continue processing 
the file, knowing what type of ParseException it was could help you do that by 
giving you the information that you need to continue - which could vary quite 
a bit depending on what went wrong.

This gets even more critical the larger your program is. The farther you get 
away from the code that threw the exception, the more worthless a generic 
exception type is (be it Exception or even something somewhat more specific 
like FileException), and the program can't really handle it. It's forced to 
either ignore it (possibly logging something), retry what it's trying to do, 
or give up on what it's trying to do. In general, handling the exceptions 
closer to their source is better, which helps, but that's not always possible.

Even a slightly more advanced exception hierarchy (e.g. having GetOptException 
with a flag, even if you don't actually derive any other exception types from 
it) would be an improvement over what we have now.

- Jonathan M Davis


More information about the Digitalmars-d mailing list