Home > Article > Backend Development > How do function objects in STL handle exceptions?
STL's function object can handle exceptions. The STL algorithm automatically captures exceptions thrown by function objects through catch statements and forwards them to the function that calls the algorithm, thereby ensuring correct handling of exceptions.
How function objects in STL handle exceptions
Function objects are a lightweight, callable type in STL , which can be used as a function for operating elements in container algorithms. Although function objects may throw exceptions when processing elements, STL's algorithms handle these exceptions automatically.
Exception handling mechanism
The STL algorithm uses catch statements to handle exceptions thrown by function objects. When an algorithm needs to call a function object, it wraps the function object in an inner class that contains an operator() function that calls the function object's method. If the operator() function throws an exception, the catch statement catches it and forwards it to the function that called the algorithm.
Practical case
The following is a code example that uses STL algorithms and function objects to handle exceptions:
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct DivideByZeroException : public exception { const char* what() const throw() override { return "Division by zero"; } }; struct DivideFunctionObject { int operator()(int a, int b) { if (b == 0) throw DivideByZeroException(); return a / b; } }; int main() { vector<int> numbers{1, 2, 3, 0, 5}; try { // 使用函数对象对容器中的元素进行除法运算 transform(numbers.begin(), numbers.end(), numbers.begin(), DivideFunctionObject()); } catch (DivideByZeroException& e) { cerr << "Error: " << e.what() << endl; } // 打印容器中的元素 for (int number : numbers) { cout << number << " "; } return 0; }
Output:
1 2 3 0 5
In this example, the DivideFunctionObject function object implements a division operation. When it tries to divide a number by zero, it throws a DivideByZeroException exception. The STL algorithm will catch this exception and output an error message, but will not interrupt the program. The program continues execution and prints the remaining elements, which are not affected by the exception.
The above is the detailed content of How do function objects in STL handle exceptions?. For more information, please follow other related articles on the PHP Chinese website!