Lambdas
Contents
Exceptions
File: except1.cpp
#include <iostream> #include <stdexcept> using namespace std ; int main() { auto divide = [](int a, int b) -> int { if (b == 0) { throw runtime_error("Division by zero!"); } return a / b; }; try { int result = divide(10, 0); cout << "Result: " << result << endl; } catch (const runtime_error& e) { cerr << "Error: " << e.what() << endl; } auto divide1 = [](int a, int b) noexcept -> int { if (b == 0) { cout << "Divisor is zero. Can't divide." << endl ; return 0; } return a / b; }; auto divide2 = [](int a, int b) noexcept -> int { if (b == 0) { cout << "Divisor is zero. Can't divide." << endl ; throw runtime_error("Division by zero!"); } return a / b; }; }
Output:
$ rm a.exe ; g++ except1.cpp ; ./a.exe
except1.cpp: In lambda function:
except1.cpp:41:14: warning: ‘throw’ will always call ‘terminate’ [-Wterminate]
41 | throw runtime_error("Division by zero!");
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error: Division by zero!
We can have a lambda expression throw an exception. The below snippet
shows how this can be done.
auto divide = [](int a, int b) -> int
{
if (b == 0) {
throw runtime_error("Division by zero!");
}
return a / b;
};
try
{
int result = divide(10, 0);
cout << "Result: " << result << endl;
}
catch (const runtime_error& e)
{
cerr << "Error: " << e.what() << endl;
}
The lambda expression checks if the divisor is 0 and if so
throws a "runbtime_error" exception which is caught later on in
a try block upon the execution of the lambda object "divide" .
auto divide1 = [](int a, int b) noexcept -> int
{
if (b == 0) {
cout << "Divisor is zero. Can't divide." << endl ;
return 0;
}
return a / b;
};
We can also have exception specification as shown above. The
"noexcept" is stating that this lambda expression does not
throw an exception.
auto divide2 = [](int a, int b) noexcept -> int
{
if (b == 0) {
cout << "Divisor is zero. Can't divide." << endl ;
throw runtime_error("Division by zero!");
}
return a / b;
};
In the above we have the "noexcept" specification but the
lambda expression throws an exception. In this case we
get a compiler warning.
Exercise
1) What does the below print ?File: except_ex1.cpp
#include <iostream> #include <stdexcept> #include <vector> using namespace std ; int main() { vector<int> v1 = { 10,20 } ; auto f1 = [=]() { cout << "Lambda Step Begin" << endl ; cout << v1.at( 2 ) << endl ; cout << "Lambda Step End" << endl ; }; try { f1(); cout << "After f1(): " << endl; } catch (const out_of_range& e) { cerr << "Error: Out of range " << endl; } return 0 ; }