www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Problem collecting exception from a passed function

reply "Gary Willoughby" <dev nomad.so> writes:
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
parent "Gary Willoughby" <dev nomad.so> writes:
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