首页 > 文章列表 > C++ 函数中如何处理异常?

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

异常处理 c++
470 2025-04-07

在 C++ 中,异常通过 try-catch 语句处理:try 块中代码可能抛出异常。catch 块捕获标准异常或自定义异常。noexcept 关键字声明函数不会抛出异常,以进行优化。

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

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

在 C++ 中,异常通过 try-catch 语句处理,包括三个主要部分:

try {
  // 代码块,可能抛出异常
}
catch (const std::exception& e) {
  // 捕获标准异常
}
catch (const MyCustomException& e) {
  // 捕获自定义异常
}

实战案例:

假设我们有一个函数 divide,它计算两个数的商,但当分母为 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;
  }
}

在主函数中,我们可以调用 divide 函数并捕获异常:

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;
  }
}

输出:

错误: 除数不能为 0

注意:

  • 函数中也可以抛出自定义异常,通过创建自定义异常类并继承 std::exception
  • 使用 noexcept 关键字声明函数不会抛出异常,以进行优化。