Exception handling is a mechanism for handling function errors, captured using try-catch syntax: the try block contains code that may cause an exception. The catch block catches exceptions of a specific type, use exception_type &e to access the exception object. catch (...) catches any type of exception. For example, when converting a string to an integer, invalid arguments raise an invalid_argument exception, and out-of-range raises an out_of_range exception.
Exception handling is a technique for handling errors or exceptions that occur within a function. It allows you to handle errors gracefully without crashing the entire program.
Exception handling uses the following syntax:
try { // 执行可能引发异常的代码 } catch (exception_type &e) { // 捕获特定类型的异常 } catch (...) { // 捕获任何类型的异常 }
try
The block contains code that may throw an exception. catch
block is used to catch specific types of exceptions. It uses the parameter exception_type &e
to access the exception object. catch (...)
. Let's look at a practical example of using exception handling:
#include <iostream> #include <string> using namespace std; int main() { try { // 将字符串转换为整数 int num = stoi("abc"); } catch (invalid_argument &e) { // 处理无效参数异常 cout << "Invalid integer: " << e.what() << endl; } catch (out_of_range &e) { // 处理超出范围异常 cout << "Out of range: " << e.what() << endl; } catch (...) { // 处理任何其他异常 cout << "Unknown error occurred." << endl; } return 0; }
In this case, we try to "abc"
Convert to integer. If the string does not contain a valid integer, it will raise an invalid_argument
exception. Alternatively, if the value is outside the int
range, an out_of_range
exception is thrown. We use exception handling to catch these exceptions and handle them gracefully.
The above is the detailed content of How to use C++ function exception handling?. For more information, please follow other related articles on the PHP Chinese website!