The Right Approach to Exceptions

Juan Manuel Cabo juanmanuel.cabo at gmail.com
Sun Feb 19 07:47:11 PST 2012


Well, since keys would be string, you can define them at the base 
class.
So, FileException can define a few detail names that you know are 
used in its derived classes. And so, Exception can define detail 
names that are standard for all classes.

So it would look like:

class FileException {
     [..]
     static immutable details_filename = "filename";
     static immutable details_ispipe = "ispipe";
     [..]
}

class Exception {
     [..]
     static immutable details_transient = "transient";
     static immutable details_i18n_name = "i18n_name";
     [..]
}


So, you *know* that a portion of the tree supports certain 
details in the associative array, when you type the dot after the 
exception class name in an IDE with autocomplete, (or ctrl-N in 
Vim with the definition open ;-) ).
And you can document with ddoc those static variables. So the 
example would be now:

For instance:

  ...
  catch (Exception ex) {
      if (Exception.details_i18n_name in ex.details) {
          log(translate(ex.details[Exception.details_i18n_name]));
      }
      if (FileException.details_filename in ex.details) {
          log("This file is trouble: "
              ~ ex.details[FileException.details_filename]);
      }
      if (Exception.details_transient in ex.details) {
          repeatOneMoreTime();
      }
  }
  ...




On Sunday, 19 February 2012 at 14:54:29 UTC, Jacob Carlborg wrote:
> On 2012-02-19 13:27, Juan Manuel Cabo wrote:
>> 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).
>
> How would you know which keys are available in "ex.details", 
> documentation?




More information about the Digitalmars-d mailing list