The Right Approach to Exceptions

Jacob Carlborg doob at me.com
Sun Feb 19 04:48:25 PST 2012


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
>

If you actually want to try and recover from the error rather than just 
simply print the error message, toString is out of the window.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list