Sub-classing exceptions

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Fri Oct 16 11:40:06 PDT 2015


On 2015-10-15 20:07, Shriramana Sharma wrote:

> $ cat except.d
> class MyException: Exception { this() { super(""); } }
> void main() { throw new MyException; }
>
> But it didn't give the expected results:
>
> $ dmd except.d
> $ ./except
> except.MyException at except.d(1)
> ...
>
> ... since the line number is wrong.

I always wondered, if the runtime can get the filename and line numbers 
for the backtrace, can't it get the same information where the exception 
was thrown?


> This is too tortuous, and methinks a mixin is in order, and since I can't do
> anything like the C preprocessor's #X stringizing, I can't declare this as a
> mixin template but have to do a string mixin:
>
> $ cat myexception.d
> string ExceptionDeclaration(string newExceptionName, string
> baseExceptionName = "Exception")
> {
>      return "class " ~ newExceptionName ~ ": " ~ baseExceptionName ~ `{
>          this(string msg = "", string file = __FILE__, size_t line =
> __LINE__)
>              { super(msg, file, line); }
>          }`;
> }

I think constructors should be inherited.

If you declare the subclass as usual you can have a template mixin that 
adds the constructor.

class SubException : Exception
{
     mixin ExceptionConstructors;
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list