Subclass of Exception

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 14 16:19:39 PDT 2014


On Sat, 14 Jun 2014 11:59:52 +0000
Paul via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> 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?

If you're creating an exception that doesn't take any new arguments (so it's
just its type that's important rather than it having any new members), then
the typical declaration would be

/++
    My exception type.
  +/
class MyException : Exception
{
    /++
        Params:
            msg  = The message for the exception.
            file = The file where the exception occurred.
            line = The line number where the exception occurred.
            next = The previous exception in the chain of exceptions, if any.
      +/
    this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) @safe pure nothrow
    {
        super(msg, file, line, next);
    }

    /++
        Params:
            msg  = The message for the exception.
            next = The previous exception in the chain of exceptions.
            file = The file where the exception occurred.
            line = The line number where the exception occurred.
      +/
    this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__) @safe pure nothrow
    {
        super(msg, file, line, next);
    }
}

There have been attempts to write mixins or templates which generate this for
you - e.g.

mixin(genExceptionType("MyException"));

but then you can't have documentation on it, because mixed-in code is not
examined when the documentation is generated, and you can't document the mixin
itself. So, at this point, it just makes the most sense to take my example,
change its name and documentation, and then use that rather than trying to
generate it - though if you don't care about documentation at all (which is
usually a bad idea but might make sense on small projects), then it would be
simple enough to create a function which will generate the string to mix in
for you.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list