c++ try catch异常处理 c++错误捕获代码

2次阅读

c++try-catch 用于捕获和处理运行时异常,提升程序健壮性;通过 try 块包裹可能出错的代码,用 catch 捕获特定类型异常,如 std::out_of_range、std::bad_alloc 等;可手动 throw 抛出异常,推荐按引用捕获以避免开销,且不应将异常用于常规流程控制。

c++ try catch 异常处理 c++ 错误捕获代码

在 C ++ 中,try-catch 机制用于处理程序运行时可能出现的异常,防止程序因未处理的错误而崩溃。通过将可能出错的代码放在 try 块中,并用 catch 捕获并处理异常,可以提高程序的健壮性。

基本语法结构

try 块包裹可能抛出异常的代码,catch 块用于捕获和处理特定类型的异常:

try {// 可能抛出异常的代码     throw exception_type(" 错误信息 "); } catch (exception_type& e) {// 处理异常     std::cout << " 捕获异常: " << e.what() << std::endl; }

常见异常类型

C++标准库 定义了多种异常类型,通常 继承 std::exception,常用的有:

  • std::invalid_argument:参数不合法
  • std::out_of_range:访问越界,如 vector 超出索引
  • std::bad_alloc:内存分配失败(new 失败)
  • std::runtime_error:运行时错误

实际使用示例

下面是一个完整的例子,演示如何使用 try-catch 处理不同类型异常:

立即学习C++ 免费学习笔记(深入)”;

#include <iostream> #include <vector> #include <stdexcept> <p>int main() { try { std::vector<int> vec = {1, 2, 3};</p><pre class='brush:php;toolbar:false;'>    // 抛出 out_of_range 异常     std::cout << vec.at(10) << std::endl;      // 下面的 new 如果失败会抛出 bad_alloc     // int* p = new int[1000000000000];  } catch (const std::out_of_range& e) {std::cout << " 越界异常: " << e.what() << std::endl; } catch (const std::bad_alloc& e) {std::cout << " 内存不足: " << e.what() << std::endl; } catch (const std::exception& e) {std::cout << " 其他标准异常: " << e.what() << std::endl; } catch (……) {std::cout << " 未知异常被捕获 " << std::endl;}  return 0;

}

手动抛出异常

你可以使用 throw 主动抛出异常,常用于函数验证输入合法性:

double divide(double a, double b) {if (b == 0.0) {throw std::invalid_argument(" 除数不能为零 ");     }     return a / b; } <p>// 使用示例 try {double result = divide(10, 0); } catch (const std::invalid_argument& e) {std::cout << " 错误: " << e.what() << std::endl; }</p>

基本上就这些。合理使用 try-catch 能让程序更稳定,但不要滥用——异常适用于“异常情况”,不应作为常规流程控制手段。同时建议捕获异常时按 引用传递 ,避免 对象 切片 和额外开销。

以上就是

站长
版权声明:本站原创文章,由 站长 2025-12-21发表,共计1462字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
1a44ec70fbfb7ca70432d56d3e5ef742
text=ZqhQzanResources