July 24, 2007
Hello!

I'm wondering if it's possible to design an exception class that would know in which line it ocurred. Without passing __LINE__ argument to it, obviosly.

Another thing I was wondering is if it would be possible for it to automatically know which function threw it, and through which functions it went. Does the new compile time reflection allows it?

Is that what's necessary to create a stack trace print with line numbers?

Cheers.
July 24, 2007
Daniel Ribeiro Maciel wrote:
> Hello!
> 
> I'm wondering if it's possible to design an exception class that would know in which line it ocurred. Without passing __LINE__ argument to it, obviosly.

I have used this template to accomplish something similar:

char[] _enforce(T)(char[] cond, char[] msg)
{
  return std.metastrings.Format!
  (
    `if (!(%s)) throw new %s ("%s: %s (in " ~ %s ~ " at " ~ %s ~ ")";`,
      cond, T.stringof, cond, msg, `__FILE__`, `ToString!(__LINE__)`
  );
}

to use it, instantiate it with a specific exception:

alias _enforce!(XException) xEnforce;

and in code:

mixin(xEnforce(`x > 0 && x < 10`, "out of range"));

The nice thing is that it will reproduce the code you check for an exception (`x > 0 && x < 10`), but a mixin is required.

How to get the function string is something that I would like to know too, if it's possible. I'd think DMD needs a __FUNCTION__









Top | Discussion index | About this forum | D home