Nerdy tidbits from my life as a software engineer

Thursday, February 26, 2009

Exception Throwing Lambdas Not Allowed

Apparently, the compiler is unable to resolve this:

public delegate T ReturnHandler<T>();
public void Whatever<T>(ReturnHandler<T> handler)
Whatever(() => throw new Exception("Doesn't work"));

You will end up getting all sorts of nasty syntax errors.  Why?  I’m not sure I understand why this can’t be parsed properly.  I suppose the lexer isn’t looking for the throw keyword when it scans the source code.  What is it looking for?  I suppose identifiers, “return”, numbers / constants (IE, true / false), and “{“.  But apparently not “throw”.  That’s kind of a bummer, and I don’t see why it can’t easily parse that expression properly.

To get around this limitation, you need to do this:

Whatever(() => { throw new Exception("Should not be necessary...but it is"); });


Jason Bock said...

IIRC you can't throw exceptions in LINQ expressions. By adding the braces it ends up being an anonymous method.

Michael J. Braude said...

But lambdas and anonymous methods are the same thing - it's just a question of whether the compiler can recognize the expression without the braces.