Home > Article > Backend Development > How do lambda expressions handle exceptions in C++?
In C, there are two ways to handle exceptions using Lambda expressions: catch the exception using a try-catch block, and handle or rethrow the exception in the catch block. Use a wrapper function of type std::functionf84160cf178f81a7d5a39a6f2f61366c whose try_emplace method can catch exceptions in Lambda expressions.
Using Lambda expressions to handle exceptions in C
Introduction
Lambda An expression is an anonymous function that captures external variables and passes parameters by value or reference. In C, lambda expressions can be used for a variety of purposes, including handling exceptions.
Using try-catch blocks
The try-catch block is the standard way to handle exceptions in Lambda expressions. The catch block allows catching specific types of exceptions or all exceptions. The following example demonstrates how to use a try-catch block in a Lambda expression to handle exceptions:
#include <functional> #include <iostream> int main() { auto lambda = [](int x) -> int { try { return x / 0; // 将引发 std::runtime_error 异常 } catch (const std::exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; return -1; } }; int result = lambda(10); std::cout << "Result: " << result << std::endl; return 0; }
Using std::function
Another way to handle exceptions in a Lambda expression The exception method is to use std::function
. std::function
is a wrapper function that can accept different function types, including Lambda expressions. std::function
provides a try_emplace
method that allows exceptions to be caught in Lambda expressions. The following example demonstrates how to use std::function
to handle exceptions:
#include <functional> #include <iostream> int main() { std::function<int(int)> lambda; try { lambda = [](int x) -> int { return x / 0; }; // 将引发 std::runtime_error 异常 } catch (const std::exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; lambda = [](int x) -> int { return -1; }; } int result = lambda(10); std::cout << "Result: " << result << std::endl; return 0; }
Practical example
Consider a function with the following interface:
int do_something(const std::string& input);
This function may raise a std::invalid_argument
exception if the input
is invalid. We can use a Lambda expression and a try-catch
block to handle this exception as follows:
auto do_something_safe = [](const std::string& input) -> int { try { return do_something(input); } catch (const std::invalid_argument& e) { // 处理异常并返回 -1 std::cout << "Invalid input: " << e.what() << std::endl; return -1; } };
We can then safely call do_something_safe
in our code , without explicitly handling the exception.
The above is the detailed content of How do lambda expressions handle exceptions in C++?. For more information, please follow other related articles on the PHP Chinese website!