Home > Article > Backend Development > How to handle function exceptions in C++?
Exception handling is a mechanism in C for handling runtime errors. Throw exceptions with throw and catch and handle them with try, catch, and finally blocks. The specific syntax is as follows: try { // Code that may cause exceptions}catch (const std::exception& e) { // Catch and handle exceptions}catch(...) { // Catch all exceptions}
How to handle function exceptions in C
Exception handling is a mechanism in C to handle runtime errors. Use the throw keyword to throw exceptions, and use try, catch, and optionally finally blocks to catch and handle exceptions.
Syntax:
try { // 可能引发异常的代码 } catch (const std::exception& e) { // 捕获并处理异常 } catch(...) { // 捕获所有异常 }
Practical example:
Consider the following function, which converts a string to an integer:
int string_to_int(std::string str) { try { int num = std::stoi(str); return num; } catch (const std::invalid_argument& e) { std::cout << "无法将字符串转换为整数" << std::endl; return -1; } catch (const std::out_of_range& e) { std::cout << "整数超出范围" << std::endl; return -1; } }
Use this function in the main function:
int main() { std::string input = "123"; int num; try { num = string_to_int(input); std::cout << num << std::endl; } catch (const std::exception& e) { std::cout << "出现异常: " << e.what() << std::endl; } return 0; }
Advantages:
The above is the detailed content of How to handle function exceptions in C++?. For more information, please follow other related articles on the PHP Chinese website!