Home >Backend Development >C++ >How to handle exceptions in C++ functions?

How to handle exceptions in C++ functions?

WBOY
WBOYOriginal
2024-04-23 15:24:01876browse

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.

C++ 函数中如何处理异常?

#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:

  • Can also be used in functions Throw a custom exception by creating a custom exception class and inheriting std::exception.
  • Use the 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn