The Right Approach to Exceptions

Jakob Ovrum jakobovrum at gmail.com
Sat Feb 18 15:47:43 PST 2012


On Saturday, 18 February 2012 at 23:26:14 UTC, Andrei 
Alexandrescu wrote:
> (b) all real code does one thing.
>
> Andrei

No. It's conceivable that *most* cases simply log the exception 
(e.g. by printing it) then either move back or move on (!). But 
it's most definitely not *all* and it's when you have a 
meaningful fall-back or recovery mechanism that exceptions shine 
and it's what they're designed for (because you are basically 
arguing against exceptions here, not their proper use, which 
should be obvious from how they function).

The more complex your program becomes, the farther away from 
uncontrollable factors like user input and otherwise unexpected 
environments you get, and this is when interesting catch blocks 
are born. Even so, exceptions are still useful in shallow parts 
of your program too - you could catch a GetOptException (more 
specific exception types than this with attached data would be 
even better, as noted by everyone before me) and re-query the 
user for new input (not very Unix-y, but that's irrelevant). You 
can't do that with just an Exception - what if the exception came 
from one of the callbacks you passed to getopt, or from a bug in 
std.getopt?

All that said, I don't think std.getopt is a good example because 
it's comparatively trivial code. std.file would be a much better 
area to examine for examples of interesting catch blocks.


More information about the Digitalmars-d mailing list