This statement doesn't compile in VS2015, but does in VS2017:
var example = new Action( () => throw new Exception()

What had to change in the way labmdas are parsed in order to support throwing an exception inside a labmda expression?
Especially because if I use a lambda body, VS2015 is perfectly happy:

My question is similar to Why can't I throw exceptions from an expression-bodied member?, but my question, is why. What had to happen in the creation of an expression tree from a lambda that necessitated extending the compiler?
In C# 6, () => had to be followed by an expression. It could be an expression that did not produce any value, such a call to a method with a return type of void, but that's still an expression.
In C# 6, throw could only appear in a statement. The complete throw new Exception("test"); is a statement. Note the semicolon in there. There was nothing in the grammar to support throw new Exception("test") on its own, the semicolon was an integral part of it.
Therefore, to get this to work, either C# 7 would have to allow statements after () => and would need to support a form of statements without the terminating ;, or C# 7 would need to extend the definition of an expression to allow throw to appear there. The latter is what happened.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With