digitalmars.D.learn - Problem collecting exception from a passed function
- Gary Willoughby (17/17) Nov 26 2013 Why in the following snippet does foo() not collect the exception
- Gary Willoughby (19/19) Nov 26 2013 Figured it out. When using lazy don't pass as a pointer and call
Why in the following snippet does foo() not collect the exception correctly? It is always null. import std.exception; import std.stdio; public void foo(A : Exception, B)(lazy B func) { auto exception = collectException(func()); writefln("%s", exception); // This is always null. } void bar() { throw new Exception("This is thrown"); } void main(string[] args) { foo!(Exception)(&bar); }
Nov 26 2013
Figured it out. When using lazy don't pass as a pointer and call at the caller site. The argument is then lazily evaluated by the called function and not by the caller. This enables passing parameters at the caller site too. import std.exception; import std.stdio; public void foo(A : Exception, B)(lazy B func) { auto exception = collectException(func()); writefln("%s", exception.msg); } void bar() { throw new Exception("This is thrown"); } void main(string[] args) { foo!(Exception)(bar()); }
Nov 26 2013