Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 674
sms Avatar asked Aug 07 '16 18:08

sms


People also ask

Can we use try catch in Lambda Python?

Nope. A Python lambda can only be a single expression.

Why are catch blocks not called functions?

The reason why your try catch block is failing is because an ajax request is asynchronous. The try catch block will execute before the Ajax call and send the request itself, but the error is thrown when the result is returned, AT A LATER POINT IN TIME. When the try catch block is executed, there is no error.

What is the function of try catch block?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

What does [=] mean in lambda function?

The [=] you're referring to is part of the capture list for the lambda expression. This tells C++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables it uses when it's created.


1 Answers

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.

like image 149
Columbo Avatar answered Oct 03 '22 22:10

Columbo