C++异常处理完全指南(最新推荐)
本文将详细讲解C++异常的抛出、捕获、栈展开、继承体系、重新抛出、异常安全、noexcept,最后手搓一个多模块项目的异常处理框架。
一、为什么需要异常
1.1 C语言的痛:错误码
回想一下C语言怎么处理错误:
// C语言风格:用返回值表示错误
int Div(int a, int b, int* result) {
if (b == 0) {
return -1; // 除0错误
}
*result = a / b;
return 0; // 成功
}
int main() {
int result;
int ret = Div(10, 0, &result);
if (ret == -1) {
printf("除0错误!\n");
} else if (ret == -2) {
printf("溢出错误!\n");
}
// 每多一种错误,就多一个if...查表过程非常繁琐
}问题很明显:
- 错误码和正常返回值混在一起,函数的返回值被占用,只能用输出参数传结果
- 错误码需要查表,拿到
-1还得去文档查这到底是什么错误 - 错误信息太少,除了一个数字,没有上下文、没有调用栈
- 逐层传递噩梦:
A→B→C→D调用链,D 出错,C/B/A 每一层都得检查返回值并继续往上传递
1.2 异常的核心思想
C++异常机制把程序分成两个角色:
- 检测方:我发现问题了,抛出一个对象,把错误信息打包扔出去,不管谁来处理
- 处理方:我能处理这种问题,在调用链的高处等着,我不管谁抛出来的
核心价值:问题的检测与问题的处理在代码上完全分离。底层函数只管报错,上层函数只管处理。
二、异常的基本用法:throw / try / catch
2.1 最简示例
#include <iostream>
#include <string>
using namespace std;
double Divide(int a, int b) {
if (b == 0) {
string s("Divide by zero condition!");
throw s; // 抛出一个异常对象,函数到此为止,后面代码不再执行
}
return (double)a / (double)b;
}
int main() {
try {
cout << Divide(10, 0) << endl; // 受监控的代码块
} catch (const string& errmsg) { // 类型匹配的异常处理
cout << "捕获到异常:" << errmsg << endl;
} catch (...) { // 兜底:捕获任意类型
cout << "未知异常" << endl;
}
return 0;
}关键语义:
throw执行时,throw 后面的语句不再执行,函数立即退出- 控制权从
throw位置直接跳转到匹配的catch块 - 会生成异常对象的拷贝(因为局部对象在栈展开中会被销毁)
2.2 多层调用链中的异常传播
这是异常最体现威力的时候——错误可以跨越 N 层函数:
void Func() {
int len, time;
cin >> len >> time;
try {
cout << Divide(len, time) << endl;
} catch (const char* errmsg) {
cout << errmsg << endl;
}
cout << __FUNCTION__ << ":" << __LINE__ << "行执行" << endl;
}
int main() {
while (1) {
try {
Func();
} catch (const string& errmsg) { // Func没catch string类型,继续往外找
cout << errmsg << endl;
} catch (...) {
cout << "未知异常" << endl;
}
}
return 0;
}调用链是 main → Func → Divide。Divide 抛出 string 异常:
- Divide 内部没有 catch
string→ 退出 Divide - Func 中 catch 的是
const char*,不匹配 → 退出 Func - main 中 catch 了
const string&,匹配成功,处理异常
三、栈展开(Stack Unwinding)
上面这个"逐层退出找 catch"的过程,就叫栈展开。
调用链: main → Func → Divide
│
throw string ← 异常从这里抛出
│
┌────┘
▼
Func 退出了吗?退了!
Func 的catch匹配吗?不匹配!
│
┌────┘
▼
main 的catch匹配吗?匹配!→ 在这里处理栈展开过程中会发生什么:
- 从 throw 位置沿着调用链逐层退出
- 每退出一个函数,该函数内的局部对象都会被正确析构(这是 RAII 的基础)
- 直到找到匹配的 catch,或者到 main 都没找到 → 调用
std::terminate终止程序
这意味着:即使出错了,栈上的资源也不会泄漏——局部对象的析构函数会被自动调用。但堆上手动 new 的资源不会自动释放,这就是后面要讲的异常安全问题。
四、异常匹配规则
4.1 精确匹配优先
// 抛出 string
throw string("hello");
// 按顺序匹配,第一个匹配的就进去
catch (int x) { } // 不匹配
catch (const string& s) { } // 匹配!进入这里
catch (string s) { } // 虽然也匹配,但前面已经进了
catch (...) { } // 兜底4.2 允许的隐式转换(重要!)
catch 匹配不是完全死板的,允许以下几种转换:
| 转换类型 | 示例 | 说明 |
|---|---|---|
| 非 const → const | string → const string& | 权限缩小,安全 |
| 派生类 → 基类 | SqlException → Exception& | 最实用!继承体系的基石 |
| 数组 → 指针 | char[10] → char* | |
| 函数 → 函数指针 | void() → void(*)() |
派生类到基类的转换,是整个企业级异常处理体系的核心。后面我们会看到,定义一个 Exception 基类,所有模块的异常都继承它,外层只 catch 基类引用就能处理所有异常——多态自动分发到正确的 what()。
4.3 catch(…) 兜底
catch (...) {
// 捕获一切,但你不知道具体是什么
cout << "未知异常" << endl;
}
通常放在 main 函数的最外层,防止异常没被处理直接 terminate。正常的业务逻辑不应该依赖它。
五、构建企业级异常继承体系
5.1 设计思路
一个小脚本不需要异常。但大型项目(微服务、数据库中间件等)有多个模块,每个模块可能出不同错误:
- SQL 模块:权限不足、语法错误、连接超时
- 缓存模块:权限不足、数据不存在
- HTTP 模块:请求资源不存在、权限不足
如果每个模块用不同的类、不同的字段,外层处理要写几十个 catch。更好的做法是:
定义一个基类
Exception,各模块继承它,外层只 catch 基类引用。
5.2 完整代码实现
#include <iostream>
#include <string>
#include <thread>
using namespace std;
// ==================== 异常基类 ====================
class Exception {
public:
Exception(const string& errmsg, int id)
: _errmsg(errmsg), _id(id) {}
virtual string what() const {
return _errmsg;
}
int getid() const {
return _id;
}
protected:
string _errmsg; // 错误描述
int _id; // 错误编号
};
// ==================== SQL 模块异常 ====================
class SqlException : public Exception {
public:
SqlException(const string& errmsg, int id, const string& sql)
: Exception(errmsg, id), _sql(sql) {}
virtual string what() const {
string str = "SqlException:";
str += _errmsg;
str += "->";
str += _sql; // 附上出错的SQL语句
return str;
}
private:
const string _sql;
};
// ==================== 缓存模块异常 ====================
class CacheException : public Exception {
public:
CacheException(const string& errmsg, int id)
: Exception(errmsg, id) {}
virtual string what() const {
string str = "CacheException:";
str += _errmsg;
return str;
}
};
// ==================== HTTP 模块异常 ====================
class HttpException : public Exception {
public:
HttpException(const string& errmsg, int id, const string& type)
: Exception(errmsg, id), _type(type) {}
virtual string what() const {
string str = "HttpException:";
str += _type; // GET/POST/PUT
str += ":";
str += _errmsg;
return str;
}
private:
const string _type;
};5.3 模拟三个服务模块
void SQLMgr() {
if (rand() % 7 == 0) {
throw SqlException("权限不足", 100, "select * from name = '张三'");
}
cout << "SQLMgr 调用成功" << endl;
}
void CacheMgr() {
if (rand() % 5 == 0) {
throw CacheException("权限不足", 100);
} else if (rand() % 6 == 0) {
throw CacheException("数据不存在", 101);
}
cout << "CacheMgr 调用成功" << endl;
SQLMgr(); // Cache里面还要调SQL
}
void HttpServer() {
if (rand() % 3 == 0) {
throw HttpException("请求资源不存在", 100, "get");
} else if (rand() % 4 == 0) {
throw HttpException("权限不足", 101, "post");
}
cout << "HttpServer 调用成功" << endl;
CacheMgr(); // HTTP里面调缓存,缓存里面还调SQL
}调用链:main → HttpServer → CacheMgr → SQLMgr,三层嵌套。
5.4 多态捕获:一行 catch 处理所有异常
int main() {
srand(time(0));
while (1) {
this_thread::sleep_for(chrono::seconds(1));
try {
HttpServer();
}
catch (const Exception& e) { // 只catch基类引用!
// 多态调用——根据实际对象类型调用对应的what()
cout << e.what() << endl;
}
catch (...) {
cout << "Unknown Exception" << endl;
}
}
return 0;
}这就是继承体系+虚函数多态的威力:
- SQL、缓存、HTTP 三个模块,各自定义了不同的异常类
- 但 main 里只需要一个
catch (const Exception& e) - 实际抛出的
SqlException对象 → 基类引用绑定 →e.what()多态调用 → 调用SqlException::what() - 以后加新模块(比如消息队列模块),只需新写一个
MqException : public Exception,main 一行不用改
六、异常的重新抛出
6.1 问题场景
有时候 catch 到异常后,不是所有情况都能处理。比如:
- 能处理的:网络不稳定导致发送失败 → 重试几次
- 不能处理的:对方已不是好友 → 这个没法重试,交给上层通知用户
这时候需要分类处理:某种错误自己处理,其他错误重新扔出去。
6.2 语法:直接 throw;
catch (const Exception& e) {
if (e.getid() == 102) {
// 能处理:网络问题,重试
} else {
throw; // 重新抛出当前捕获的异常对象
}
}注意:throw; 不加参数,表示把当前 catch 到的异常对象原样抛出。不是 throw e;——throw e; 会生成一个新拷贝,而且如果 e 是基类引用,throw e; 会按基类类型抛出,丢失派生类信息。
6.3 实战:带重试的发送消息
// 底层发送函数:可能抛异常
void _SendMsg(const string& s) {
if (rand() % 2 == 0) {
throw HttpException("网络不稳定,发送失败", 102, "put"); // 可重试
} else if (rand() % 7 == 0) {
throw HttpException("你已经不是对方的好友,发送失败", 103, "put"); // 不可重试
}
cout << "发送成功" << endl;
}
// 上层:带重试逻辑
void SendMsg(const string& s) {
for (size_t i = 0; i < 4; i++) { // 最多重试3次
try {
_SendMsg(s);
break; // 发送成功,退出循环
}
catch (const Exception& e) {
if (e.getid() == 102) { // 102号:网络问题,可重试
if (i == 3) {
throw; // 重试3次都失败,认命,往上抛
}
cout << "开始第" << i + 1 << "次重试" << endl;
} else {
throw; // 不是网络问题,不重试,直接往上抛
}
}
}
}
// 最上层:展示结果给用户
int main() {
srand(time(0));
string str;
while (cin >> str) {
try {
SendMsg(str);
}
catch (const Exception& e) {
cout << e.what() << endl << endl;
}
catch (...) {
cout << "Unknown Exception" << endl;
}
}
return 0;
}三层分工清晰:
| 层级 | 职责 |
|---|---|
_SendMsg | 检测问题,抛出具体异常 |
SendMsg | 分类处理:能重试的重试,不能的重新抛出 |
main | 最终兜底:通知用户 |
七、异常安全问题
7.1 异常 + 裸指针 = 资源泄漏
void Func() {
int* array = new int[10]; // ① 申请堆内存
int len, time;
cin >> len >> time;
cout << Divide(len, time) << endl; // ② 如果这里抛异常了……
delete[] array; // ③ 这行根本执行不到!
}如果 Divide 抛出异常,delete[] array 永远不会执行 → 10个int的内存泄漏。
7.2 解决方案:catch后重新抛出
void Func() {
int* array = new int[10];
try {
int len, time;
cin >> len >> time;
cout << Divide(len, time) << endl;
}
catch (...) {
// 不管什么异常,先释放资源
delete[] array;
throw; // 再把异常原样抛出去,让上层处理
}
delete[] array;
}套路:catch 住 → 释放自己负责的资源 → 重新 throw,让上层继续处理业务逻辑。
7.3 更好的方案:RAII
当然,手动 new/delete + catch 重新抛出太容易出错了。C++ 的最佳实践是 RAII(Resource Acquisition Is Initialization)——用智能指针、容器等自动管理资源的类,它们在栈展开时会被自动析构,不需要手动清理。关于智能指针的内容,我们在下一篇文章中讲解。
7.4 析构函数中的异常——千万别让它逃出去
~MyClass() {
// 析构函数要释放10个资源
// 如果释放到第5个时抛异常,后面5个就泄漏了
// 所以析构函数内部要做好try/catch,别让异常逃出去
try {
// 释放资源
} catch (...) {
// 吞掉异常或记录日志,但不往外抛
}
}八、noexcept:承诺不抛异常
8.1 C++98 的异常规范(已被历史淘汰)
// C++98 风格:函数后面写 throw(可能抛的类型) void* operator new (size_t size) throw (std::bad_alloc); // 可能抛 bad_alloc void* operator delete (void* ptr) throw(); // 不抛异常 // 过于复杂,实践中没人用,C++11 废弃了
8.2 C++11 noexcept
// C++11 简洁版 size_type size() const noexcept; // 承诺不抛异常 iterator begin() noexcept; // 承诺不抛异常
关键认知:
- 编译器不强制检查——你用
noexcept修饰了函数,但里面调了 throw,编译器照样编译通过(顶多给个警告) - 运行时的处理——声明了
noexcept的函数如果真的抛了异常,程序会调用std::terminate终止 - 移动构造/移动赋值尽量加
noexcept——这样 STL 容器在做扩容等操作时才会优先用移动而非拷贝
8.3 noexcept 运算符
#include <list>
double Divide(int a, int b) {
if (b == 0) throw "Division by zero condition!";
return (double)a / (double)b;
}
int main() {
int i = 0;
// noexcept(表达式) 在编译期判断表达式是否会抛异常
cout << noexcept(Divide(1, 2)) << endl; // 0 (false) —— 可能抛异常
cout << noexcept(Divide(1, 0)) << endl; // 0 (false) —— 可能抛异常
cout << noexcept(++i) << endl; // 1 (true) —— ++i 不抛异常
list<int> lt;
cout << noexcept(lt.begin()) << endl; // 1 (true) —— begin() 声明了 noexcept
return 0;
}
noexcept运算符判断的是表达式本身是否可能抛异常,不是判断这次调用会不会抛。Divide(1, 0)确实会抛异常,但noexcept只看函数的声明,Divide没有声明noexcept,所以返回 false。
九、标准库的异常体系
C++ 标准库也有一套自己的异常继承体系:
std::exception ← 基类,virtual const char* what() ├── std::logic_error ← 逻辑错误(可在编译期检测) │ ├── std::invalid_argument │ ├── std::out_of_range │ └── std::length_error ├── std::runtime_error ← 运行时错误 │ ├── std::overflow_error │ ├── std::range_error │ └── std::system_error └── std::bad_alloc ← new 失败
日常写程序时,主函数里 catch const std::exception& e,然后调 e.what() 就能获取错误信息。
int main() {
try {
// 你的程序
}
catch (const exception& e) {
cout << "标准库异常:" << e.what() << endl;
}
catch (...) {
cout << "未知异常" << endl;
}
return 0;
}你自己的异常体系也可以继承 std::exception 并重写 what(),这样和标准库风格统一。
十、总结
| 知识点 | 核心要点 |
|---|---|
| 基本语法 | throw 抛对象 → 沿调用链找 catch → 类型匹配就进去 |
| 栈展开 | 逐层退出函数,局部对象自动析构,直到找到匹配的 catch |
| 匹配规则 | 精确匹配 ,但允许派生类→基类、非const→const 等隐式转换 |
| 继承体系 | 定义 Exception 基类+虚函数 what(),各模块继承,外层只 catch 基类引用 |
| 重新抛出 | throw; 不加参数,把当前异常原样再抛(不要用 throw e;) |
| 异常安全 | 裸指针 + 异常 = 泄漏;用 RAII 或在 catch 中释放后重新 throw |
| noexcept | 承诺不抛异常;声明了但抛了会 terminate;移动构造尽量加 |
| 标准库 | std::exception 是标准异常的基类,what() 是虚函数 |
异常处理的完整思路:底层负责检测和抛出(携带足够信息),中层负责分类和重试,顶层负责兜底和通知用户。配上一个设计良好的异常继承体系,几十万行的项目也只需要一行 catch。
到此这篇关于C++异常处理完全指南的文章就介绍到这了,更多相关C++异常处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
C++无法从“const char[ ]”转换为“char *”问题及解决
这篇文章主要介绍了C++无法从“const char[ ]”转换为“char *”问题及解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-04-04
Visual Studio Code 配置C、C++ 文件debug调试环境的详细过程
这篇文章主要介绍了Visual Studio Code 配置C、C++ 文件debug调试环境,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-02-02


最新评论