Throw an exception but "hide" the top frame?

aldanor via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Dec 24 05:38:59 PST 2014


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 at 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 at wrap.d(21): -3 < 0
     ----------------
     .. (_Dmain+0x20) [0x448da4]



More information about the Digitalmars-d-learn mailing list