The Right Approach to Exceptions
deadalnix at gmail.com
Sat Feb 18 17:08:22 PST 2012
Le 19/02/2012 01:36, H. S. Teoh a écrit :
> 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):
>> 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.
I hope somebody will listen to you !
More information about the Digitalmars-d