The Right Approach to Exceptions
Jonathan M Davis
jmdavisProg at gmx.com
Sat Feb 18 16:37:04 PST 2012
On Saturday, February 18, 2012 16:36:16 H. S. Teoh wrote:
> 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.
And in order to programmatically handle exceptions rather than simply print
out messages, that hierarchy and the extra information that the derived
exceptions give is necessary.
- Jonathan M Davis
More information about the Digitalmars-d