Subclass of Exception

FreeSlave via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 14 05:17:44 PDT 2014


On Saturday, 14 June 2014 at 11:59:53 UTC, Paul wrote:
> One stupid question: in Python subclassing of Exception looks 
> like:
>   class MyError(Exception): pass
> but in D, if I'm right, we should write more code:
>   class MyError : Exception {
>     this(string msg) { super(msg); }
>   }
> (without constructor we get error: "...Cannot implicitly 
> generate a default ctor when base class <BASECLASS> is missing 
> a default ctor...")
>
> Is any shorter D way?

In this regard D is same as C++. When you create derived class, 
you need to define constructors, even if all they do is passing 
arguments to base class' constructor. It's really annoying, 
especially when base class has many constructors.
But in D you can apply some template magic to automate this 
process for exceptions.
Example:

import std.stdio;

template TemplateException(T)
{
     class TemplateException : Exception
     {
     public:
         this(string msg, string file = __FILE__, size_t line = 
__LINE__, Throwable next = null) {
             super(msg, file, line, next);
         }
     }
}

void throwException(Exception ex)
{
     try {
         throw ex;
     }
     catch(TemplateException!int e) {
         writeln("int");
     }
     catch(TemplateException!double e) {
         writeln("double");
     }
     catch(TemplateException!string e) {
         writeln("string");
     }
}

int main()
{
     auto intEx = new TemplateException!int("int error");
     auto doubleEx = new TemplateException!double("double error");
     auto stringEx = new TemplateException!string("string error");

     throwException(intEx);
     throwException(doubleEx);
     throwException(stringEx);
     return 0;
}

You also can tempalte with string literals instead of types to 
gain more flexibility and use alias statement to provide 
convenient names.


More information about the Digitalmars-d-learn mailing list