The Right Approach to Exceptions

Jim Hewes jimhewes at
Sun Feb 19 14:53:04 PST 2012

On 2/18/2012 3:13 PM, Andrei Alexandrescu wrote:
> On 2/18/12 4:26 PM, Jonathan M Davis wrote (abridged):
> GetOptException
> FlagArgumentMissingException
> InvalidFlagArgumentException
> UnknownFlagException
> FileException
> FileNotFoundException
> NotFileException
> NotDirException
> AccessDeniedException
> I died inside a little.
> Andrei

IMHO, I would not have made a GetOptException at all. It is too specific 
to the function. Since this is a type of parse error, I would prefer a 
ParseException base class. I think has a couple of advantages. One, the 
same exception can be used not only by the library itself but also by 
other users. Parsing is not an uncommon activity. Two, the exception 
hierarchy is orthogonal to the library. So changing the library 
functions---adding or removing them--- doesn't require changes in the 
exception hierarchy. Perhaps ParseException could then have a field that 
highlights the text that could not be parsed. This could be generally 
for all parsing type application.

In separating what should be a distinct type from what should be an 
attribute, I'd think you can use as a guideline whether the errors are 
likely to be handled in one place. I would guess that if you're going to 
try to analyze a parse error you would handle the possibilities of 
FlagArgumentMissingException, InvalidFlagArgumentException, and 
UnknownFlagException all in one place. You're not likely to catch one 
and let the others propagate upward. So those could be attribute you 
handle with a switch rather than separate types.


More information about the Digitalmars-d mailing list