The Right Approach to Exceptions

Juan Manuel Cabo juanmanuel.cabo at gmail.com
Sun Feb 19 04:27:51 PST 2012


How about adding a string[string] or a variant[string] to the 
Exception class, so one can know details about the subclassed 
exception without downcasting? How ugly would that be?

For instance:

     ...
     catch (Exception ex) {
       if ("transient" in ex.details) {
             repeatOneMoreTime();
       }
       if ("i18n_code" in ex.details) {
             log(translate(ex.details["i18n_code"]));
       }
     }
     ...

Details can be standard by convention or otherwise custom.
(I can see that this can lead to messy proliferation of details, 
but at least solves most of the issues).

--jm (BIG FAN OF D. GUYS I LOVE ALL YOUR GOOD WORK)




On Sunday, 19 February 2012 at 08:06:38 UTC, Andrei Alexandrescu 
wrote:
> On 2/19/12 1:12 AM, Jonathan M Davis wrote:
>> On Sunday, February 19, 2012 00:43:58 Andrei Alexandrescu 
>> wrote:
>>> On 2/18/12 8:00 PM, H. S. Teoh wrote:
>>>>>   From this and other posts I'd say we need to design the 
>>>>> base exception
>>>>>
>>>>> classes better, for example by defining an overridable 
>>>>> property
>>>>> isTransient that tells caller code whether retrying might 
>>>>> help.
>>>>
>>>> Just because an exception is transient doesn't mean it makes 
>>>> sense to
>>>> try again. For example, saveFileMenu() might read a filename 
>>>> from the
>>>> user, then save the data to a file. If the user types an 
>>>> invalid
>>>> filename, you will get an InvalidFilename exception. From an 
>>>> abstract
>>>> point of view, an invalid filename is not a transient 
>>>> problem: retrying
>>>> the invalid filename won't make the problem go away. But the 
>>>> application
>>>> in this case *wants* to repeat the operation by asking the 
>>>> user for a
>>>> *different* filename.
>>>>
>>>> On the other hand, if the same exception happens in an app 
>>>> that's trying
>>>> to read a configuration file, then it *shouldn't* retry the 
>>>> operation.
>>>
>>> I'm thinking an error is transient if retrying the operation 
>>> with the
>>> same exact data may succeed. That's a definition that's 
>>> simple, useful,
>>> and easy to operate with.
>>
>> A core problem with the idea is that whether or not it makes 
>> sense to try
>> again depends on what the caller is doing. In general, I think 
>> that it's best
>> to give the caller as much useful information is possible so 
>> that _it_ can
>> decide the best way to handle the exception.
>
> That sounds like "I violently agree".
>
> Andrei




More information about the Digitalmars-d mailing list