The Right Approach to Exceptions

Jacob Carlborg doob at me.com
Sun Feb 19 08:40:14 PST 2012


On 2012-02-19 15:38, Andrei Alexandrescu wrote:
> On 2/19/12 6:49 AM, Jacob Carlborg wrote:
>> On 2012-02-19 01:09, Andrei Alexandrescu wrote:
>>> On 2/18/12 6:03 PM, Jonathan M Davis wrote:
>>>> On Saturday, February 18, 2012 17:30:10 Andrei Alexandrescu wrote:
>>>>> The alternative is with virtuals. Do you see a lot of virtuals in base
>>>>> exceptions? Do you see dramatically different interface for different
>>>>> exception types?
>>>>
>>>> You mean virtual functions? The problem is that each exception type
>>>> could have
>>>> information specific to _it_ which makes no sense in a base class. For
>>>> instance, Exception does to have errno in it. FileException does.
>>>>
>>>> If we have GetOptException, it should have a variable for which flag
>>>> failed.
>>>> Exception doesn't have that. And what if the flag failed because it
>>>> was given a
>>>> bad argument? Then the exception needs a field for that argument. Then
>>>> you can
>>>> get something like
>>>>
>>>> try
>>>> getopt(args, ...)
>>>> catch(MissingArgumentException mae)
>>>> {
>>>> stderr.writefln("%s is missing an argument", mae.flag);
>>>> return -1;
>>>> }
>>>> catch(InvalidArgumentException iae)
>>>> {
>>>> stderr.writelfln("%s is not a valid argument for %s. You must give it a
>>>> %s.", mae.arg, mae.flag, mae.expectedType);
>>>> return -1;
>>>> }
>>>> catch(UnknownFlagException ufe)
>>>> {
>>>> stderr.writefln("%s is not a known flag.", ufe.ufe);
>>>> return -1;
>>>> }
>>>> catch(GetOptException goe)
>>>> {
>>>> stderr.writefln("There was an error with %s", goe.flag);
>>>> return -1;
>>>> }
>>>> //A delegate that you passed to getopt threw an exception.
>>>> catch(YourException ye)
>>>> {
>>>> //...
>>>> }
>>>> catch(Exception e)
>>>> {
>>>> stderr.writeln("An unexpected error occured.");
>>>> return -1;
>>>> }
>>>>
>>>> You can't do _anything_ like that right now.
>>>
>>> Of course I can. They call it toString(). The code above pretty much
>>> proves my point with so much wonderful irony.
>>>
>>> Andrei
>>>
>>
>> Say you want to do something like what Git does:
>>
>> $ git statu
>> git: 'statu' is not a git command. See 'git --help'.
>>
>> Did you mean this?
>> status
>> $
>>
>> That would be quite hard with just toString.
>
> An exception hierarchy won't make that easier or more modular. What's
> needed there is the command and a table of all commands.
>
> Andrei

The command could be in the exception. Then you would have to look it up 
against all valid commands. For the command to be in the exception you 
would need some sort of hierarchy because, as others have said, a 
command property wouldn't make sense for an exception like FileNotFound, 
and wouldn't make sense in the base class Exception.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list