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

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

异常处理 c++
488 2024-04-23

异常处理是 C++ 中用于处理运行时错误的机制。通过 throw 抛出异常,并使用 try、catch 和 finally 代码块捕获和处理异常。具体语法如下:try { // 可能引发异常的代码 }catch (const std::exception& e) { // 捕获并处理异常 }catch(...) { // 捕获所有异常 }

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

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

异常处理是 C++ 中处理运行时错误的一种机制。使用 throw 关键字抛出异常,并使用 try、catch 和可能选项 finally 代码块来捕获和处理异常。

语法:

try {
  // 可能引发异常的代码
} catch (const std::exception& e) {
  // 捕获并处理异常
} catch(...) {
  // 捕获所有异常
}

实战案例:

考虑以下函数,该函数将字符串转换为整数:

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

在主函数中使用该函数:

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

优点:

  • 提高程序健壮性
  • 允许在特定位置处理特定异常
  • 提供错误信息和自定义错误处理
  • 防止程序意外终止