List of exceptions?

Ali Çehreli acehreli at yahoo.com
Sat Oct 10 18:16:45 UTC 2020


On 10/10/20 9:16 AM, DMon wrote:

 > catch (Exception e) // implicit (any exception)
 > catch (ConvException f) // explicit (conversion only)
 >
 > Or is that not correct?

I think in class hierarchies, "more general" and "more specific" are 
better terms. :)

The answer is, catch by the most general under the Exception hierarchy 
that you care about. It depends on the program. In most of my programs, 
catching Exception in main is sufficient because I just print the error 
message.

However, sometimes the error message does not make sense at that level:

void foo() {
   // The error thrown during this may not be meaningful to
   // the user of the program:
   // "Unexpected 'h' when converting from type string to type int"
   "hello".to!int;
}

So, you can augment that error with another one:

import std.conv;
import std.stdio;
import std.format;

class FooException : Exception {
   string msg;
   Exception actual;

   this (Exception e) {
     this.msg = format!"Failed to do foo: %s"(e.msg);
     super(this.msg);
     this.actual = e;  // Store for more information later
   }
}

void foo() {
   try {
     "hello".to!int;

   } catch (Exception e) {
     // Convert to a more meanigful exception:
     throw new FooException(e);
   }
}

int main() {
   try {
     foo();

   } catch (Exception e) {
     stderr.writefln!"ERROR: %s"(e.msg);
     return 1;
   }

   return 0;
}

One cool thing about storing the 'actual' exception is, you can later 
debug it by catching the specific FooException and printing 'actual' as 
is, which contains the stack trace:

int main() {
   try {
     foo();

   // Added for debugging:
   } catch (FooException e) {
     // Printing as is contains the stack trace:
     stderr.writeln(e.actual);
     return 1;

   } catch (Exception e) {
     stderr.writefln!"ERROR: %s"(e.msg);
     return 1;
   }

   return 0;
}

But really, it all depends on your program. The simplest thing may to 
not catch at all. The default behavior is to dump the stack trace and it 
works for some programs.

Ali



More information about the Digitalmars-d-learn mailing list