如何处理 C++ 函数中未捕获的异常?(捕获.如何处理.函数.中未.异常...)

wufei123 发布于 2024-08-21 阅读(29)

处理未捕获的 c++++ 异常有以下方法:1. 使用 try-catch 块;2. 使用 set_terminate 函数;3. 使用 __try-__finally 语句。在实战中,可以使用 try-catch 块处理潜在的异常,使其不会导致程序意外终止。

如何处理 C++ 函数中未捕获的异常?

如何处理 C++ 函数中未捕获的异常?

在 C++ 中,未捕获的异常会导致程序意外终止。为了防止这种情况,可以通过以下方式处理未捕获的异常:

1. 使用 try-catch 块
try {
  // 可能抛出异常的代码
}
catch (const std::exception& e) {
  // 处理异常
}
2. 使用 set_terminate 函数

set_terminate 函数允许您指定在发生未捕获的异常时调用的函数。该函数应该接受一个 std::exception_ptr 参数,其中包含有关异常的信息。

std::set_terminate([](std::exception_ptr p) {
  // 处理异常
});
3. 使用 __try-__finally 语句

__try-__finally 语句确保无论是否抛出异常,都执行指定的代码块。

__try {
  // 可能抛出异常的代码
}
__finally {
  // 清理代码
}
实战案例

考虑以下代码,它使用 try-catch 块处理潜在的异常:

void divide(int a, int b) {
  try {
    if (b == 0) throw std::runtime_error("除以零错误");
    std::cout << (a / b) << std::endl;
  }
  catch (const std::runtime_error& e) {
    std::cout << e.what() << std::endl;
  }
}

使用此函数:

int main() {
  divide(10, 2);  // 输出 5
  divide(10, 0);  // 输出 "除以零错误"
  return 0;
}

以上就是如何处理 C++ 函数中未捕获的异常?的详细内容,更多请关注知识资源分享宝库其它相关文章!

标签:  捕获 如何处理 函数 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。