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

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

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

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

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

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

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

登录后复制

实战案例:

假设我们有一个函数 pide,它计算两个数的商,但当分母为 0 时抛出异常:

int pide(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;
  }
}

登录后复制

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

int main() {
  try {
    int pidend = 10;
    int pisor = 0;
    int result = pide(pidend, pisor);
    std::cout << pidend << " / " << pisor << " = " << result << std::endl;
  }
  catch (const std::runtime_error& e) {
    std::cout << e.what() << std::endl;
  }
}

登录后复制

输出:

错误: 除数不能为 0

登录后复制

注意:

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

以上就是C++ 函数中如何处理异常?的详细内容,更多请关注叮当号网其它相关文章!

文章来自互联网,只做分享使用。发布者:代号邱小姐,转转请注明出处:https://www.dingdanghao.com/article/391645.html

(0)
上一篇 2024-04-23 16:01
下一篇 2024-04-23 16:01

相关推荐

联系我们

在线咨询: QQ交谈

邮件:442814395@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信公众号