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?
Nope. A Python lambda can only be a single expression.
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.
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.
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.
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.
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