Home >Backend Development >C++ >How to handle exceptions in C++ functions?
In C, exceptions are handled through the try-catch statement: the code in the try block may throw an exception. The catch block catches standard exceptions or custom exceptions. The noexcept keyword declares that the function will not throw exceptions for optimization.
#How to handle exceptions in C functions?
In C, exceptions are handled through the try-catch
statement, which includes three main parts:
try { // 代码块,可能抛出异常 } catch (const std::exception& e) { // 捕获标准异常 } catch (const MyCustomException& e) { // 捕获自定义异常 }
Practical case:
Suppose we have a function divide
that calculates the quotient of two numbers, but throws an exception when the denominator is 0:
int divide(int num, int denom) { try { if (denom == 0) { throw std::runtime_error("除数不能为 0"); } return num / denom; } catch (const std::exception& e) { std::cout << "错误: " << e.what() << std::endl; } }
In the main function, we can Call the divide
function and catch the exception:
int main() { try { int dividend = 10; int divisor = 0; int result = divide(dividend, divisor); std::cout << dividend << " / " << divisor << " = " << result << std::endl; } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; } }
Output:
错误: 除数不能为 0
Note:
std::exception
. noexcept
keyword to declare that the function will not throw exceptions for optimization. The above is the detailed content of How to handle exceptions in C++ functions?. For more information, please follow other related articles on the PHP Chinese website!