On Wed, 24 Dec 2014 13:38:59 +0000
aldanor via Digitalmars-d-learn <digitalmars-d-learn@puremagic.com>
wrote:

> Imagine there's a template that wraps arbitrary functions and may 
> throw exceptions depending on their returned values (see a 
> simplified example below). However, if an exception occurs, the 
> backtrace is pointing inside the template which is not helpful at 
> all (especially when many such functions have been wrapped). Is 
> it somehow possible to throw an exception "from the parent frame" 
> so the backtrace would never drop into the template body?
> 
> Here's an example:
> 
>      module wrap;
> 
>      import std.stdio;
>      import std.string;
> 
>      auto check(alias func)(int x) {
>          auto result = func(x);
>          if (result < 0) // throw on negative return value
>              throw new Exception("%d < 0".format(result)); // L10
>          return x; // otherwise, pass the result through
>      }
> 
>      int f(int x) {
>          return !(x % 2) ? x : -x;
>      }
> 
>      void main() {
>          import std.stdio;
>          alias g = check!f;
>          writeln(g(2)); // ok
>          writeln(g(3)); // should fail // L21
>      }
> 
> which prints something lke this when run:
> 
>      2
>      object.Exception@wrap.d(10): -3 < 0
>      ----------------
>      .. (int wrap.check!(_D4wrap1fFiZi).check(int)+0x13) [0x44cf87]
>      .. (_Dmain+0x20) [0x448da4]
> 
> Is it possible to throw an exception in a way that backtrace 
> would be more like this?
> 
>      2
>      object.Exception@wrap.d(21): -3 < 0
>      ----------------
>      .. (_Dmain+0x20) [0x448da4]
> 
the `object.Exception@wrap.d` is not a backtrace result, this is the
result of Exception class constructor:

  this (string msg, string file=__FILE__, usize line=__LINE__, Throwable 
next=null)

it registering the file and line of exception object creation in
COMPILE time. so you can do nothing with it, as there is no way to know
what called what in compile time.

p.s. if you can use GDC, for example, and turn on debug info,
backtrace will show you files and line numbers for every address.

Attachment: signature.asc
Description: PGP signature

Reply via email to