The Right Approach to Exceptions

H. S. Teoh hsteoh at
Sat Feb 18 16:36:16 PST 2012

On Sat, Feb 18, 2012 at 05:13:16PM -0600, 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.

That's because you're missing the hierarchy, which may look more like

     +--GetOptException (bad name, I prefer CommandLineException)
     |   +--FlagArgumentMissingException
     |   +--InvalidFlagArgumentException
     |   +--UnknownFlagException
     |   +--FileNotFoundException
     |   +--NotFileException
     |   +--NotDirException
     |   +--AccessDeniedException
     +--IOException (OK, I added this branch, just to show the idea)

So if all you care about is to handle command-line option parse errors,
and don't care which error it is, you could just catch GetOptException.
If all you care about is file access exceptions, you can just catch
FileException without having to worry which specific exception it is.

Alternatively, if you don't care which exception it is at all, then
just catch Exception.

That's the whole point of a (well-designed) exception hierarchy. It lets
you be as generic or as specific as you want.

Note also, that an elaborated exception hierarchy lets you attach
additional specific information that might be useful in error recovery.
For example, FileException may have a field containing the filename that
caused the error, so that if the program is processing a list of
filenames, it knows which one went wrong. You would not want such
information in Exception, because it only applies to FileException's.

Similarly, GetOptException (or CommandLineException) may have additional
fields to indicate which option is malformed. Such information,
obviously, shouldn't be in other kinds of exceptions but those that
inherit GetOptException.


Which is worse: ignorance or apathy? Who knows? Who cares? -- Erich Schubert

More information about the Digitalmars-d mailing list