sms sms - 4 months ago 11
C++ Question

Why there is no function-try-block for lambda?

void foo() try {} catch (...) {}
// OK, function-try-block




[]() try {} catch (...) {} ();
// error: expected ‘{’ before ‘try’




[]() { try {} catch (...) {} } ();
// OK, extra curly braces`


Why is the second variant not allowed?

Answer

Originally, function-try-blocks were introduced to be able to catch exceptions thrown in constructors or destructors of subobjects. The syntax was extended to normal functions for consistency.

It would, of course, be possible to introduce such syntax for lambdas. However, as opposed to constructors and destructors, there is no practical advantage over simply enclosing the try-block in another pair of { }, except the latter looks much less obscure.