The Right Approach to Exceptions

Juan Manuel Cabo juanmanuel.cabo at
Tue Feb 21 08:50:42 PST 2012

> throw new WithRainbows!withErrorCode!withFoobar!FileNotFoundException(...);


    catch (WithRainbows!withErrorCode!withFoobar!FileNotFoundException ex) {
    } catch (WithRainbows!withErrorCode!withFoobar!FileNotFoundException ex) {
    } catch (WithErrorCode!withRainbows!withFoobar!FileNotFoundException ex) {
    } catch (WithRainbows!withFoobar!withErrorCode!FileNotFoundException ex) {

and so on (in this case will be, its 3! == 6).

and you would have to write them all. You cannot catch only WithRainbows!* because
you miss the FileNotFoundException at the end.

Please, refer to my previous posts.
I don't want to start to repaste my posts.
In one of them, I said that what you care about for the catch selection
is the *what* of the error.   Not the *cause* of the error, not the *where*
of the error (no one catches by *where*). And that it seems wrong to encode
anything other than the *what* of the error in the type name. Other things
such as the cause or the date should be encoded inside the exception object
instead of in the exception class type name.

I thought that an alternative to Variant[string] would be to have some virtual
functions overrideable (getExceptionData(string dataName) or something).
but they would all have to return Object or Variant, so it's the same thing.


On 02/21/2012 01:39 PM, foobar wrote:
> On Tuesday, 21 February 2012 at 16:15:17 UTC, Juan Manuel Cabo wrote:
>>> FileNotFoundException is the super class of the others so the first catch clause is enough. in fact, the others will
>>> never be called if listed in the above order.
>> Nice! I missed that. But what if you want to add ErrorCode and Rainbows?
>> And with your approach, one has to test for type and downcast, or
>> otherwise have multiple catch blocks (I don't want to miss plain
>> FileNotFoundExceptions). So it's square one.
>> With Variant[string] (or something equivalent, nothing better comes to mind)
>> one does:
>>     try {
>>         ...
>>     } catch (FileNotFoundException ex) {
>>          if (ex.hasInfo(MyNameConstant)) {
>>              ... use that ...
>>          }
>>          ... common handling ...
>>     }
>> --jm
> Regarding the downcast - you still perform a check in the code above! You gained nothing by replacing a type check with
> a check on a hash.
> Regarding composition of several traits - even that simple snippet is enough:
> throw new WithRainbows!withErrorCode!withFoobar!FileNotFoundException(...);
> That's without further design which could probably improve this further.

More information about the Digitalmars-d mailing list