C++异常机制通过将错误检测与处理分离,解决C语言错误码返回值与错误码混合、查表繁琐、缺乏上下文及逐层传递等问题。合理设计异常体系能提升代码健壮性与可维护性,基本用法包含throw、try和catch。
C++异常处理是提升代码健壮性的核心技术,很多C++开发者最初认为异常机制过于复杂且性能开销较大,甚至选择禁用异常。然而在深入大型项目后会发现,合理设计的异常体系能够显著提升代码的健壮性和可维护性。本文将从C语言错误处理的痛点出发,逐步解析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 每一层都得检查返回值并继续往上传递C++异常机制将程序划分为两个角色:
核心价值:问题的检测与问题的处理在代码上完全分离。底层函数只负责报错,上层函数只负责处理。
#include#include 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 块这是异常最体现威力的时候——错误可以跨越 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 异常:
string→ 退出 Divideconst char*,不匹配 → 退出 Funcconst string&,匹配成功,处理异常上面这个"逐层退出找 catch"的过程,就叫栈展开。
调用链: main → Func → Divide
│
throw string ← 异常从这里抛出
│
┌────┘
▼
Func 退出了吗?退了!
Func 的catch匹配吗?不匹配!
│
┌────┘
▼
main 的catch匹配吗?匹配!→ 在这里处理
栈展开过程中会发生什么:
std::terminate 终止程序这意味着:即使出错了,栈上的资源也不会泄漏——局部对象的析构函数会被自动调用。但堆上手动 new 的资源不会自动释放,这就是后面要讲的异常安全问题。
// 抛出 string
throw string("hello");
// 按顺序匹配,第一个匹配的就进去
catch (int x) { } // 不匹配
catch (const string& s) { } // 匹配!进入这里
catch (string s) { } // 虽然也匹配,但前面已经进了
catch (...) { } // 兜底
catch 匹配不是完全死板的,允许以下几种转换:
| 转换类型 | 示例 | 说明 |
|---|---|---|
| 非 const → const | string → const string& | 权限缩小,安全 |
| 派生类 → 基类 | SqlException → Exception& | 最实用!继承体系的基石 |
| 数组 → 指针 | char[10] → char* | |
| 函数 → 函数指针 | void() → void(*)() |
派生类到基类的转换,是整个企业级异常处理体系的核心。后面我们会看到,定义一个 Exception 基类,所有模块的异常都继承它,外层只 catch 基类引用就能处理所有异常——多态自动分发到正确的 what()。
catch (...) {
// 捕获一切,但你不知道具体是什么
cout << "未知异常" << endl;
}
通常放在 main 函数的最外层,防止异常没被处理直接 terminate。正常的业务逻辑不应该依赖它。
一个小脚本不需要异常。但大型项目(微服务、数据库中间件等)有多个模块,每个模块可能出不同错误:
如果每个模块用不同的类、不同的字段,外层处理要写几十个 catch。更好的做法是:
定义一个基类
Exception,各模块继承它,外层只 catch 基类引用。
#include#include #include 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; };
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,三层嵌套。
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;
}
这就是继承体系+虚函数多态的威力:
catch (const Exception& e)SqlException 对象 → 基类引用绑定 → e.what() 多态调用 → 调用 SqlException::what()MqException : public Exception,main 一行不用改有时候 catch 到异常后,不是所有情况都能处理。比如:
这时候需要分类处理:某种错误自己处理,其他错误重新扔出去。
catch (const Exception& e) {
if (e.getid() == 102) {
// 能处理:网络问题,重试
} else {
throw; // 重新抛出当前捕获的异常对象
}
}
注意:throw; 不加参数,表示把当前 catch 到的异常对象原样抛出。不是 throw e;——throw e; 会生成一个新拷贝,而且如果 e 是基类引用,throw e; 会按基类类型抛出,丢失派生类信息。
// 底层发送函数:可能抛异常
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 | 最终兜底:通知用户 |
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的内存泄漏。
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,让上层继续处理业务逻辑。
当然,手动 new/delete + catch 重新抛出太容易出错了。C++ 的最佳实践是 RAII(Resource Acquisition Is Initialization)——用智能指针、容器等自动管理资源的类,它们在栈展开时会被自动析构,不需要手动清理。关于智能指针的内容,我们在下一篇文章中讲解。
~MyClass() {
// 析构函数要释放10个资源
// 如果释放到第5个时抛异常,后面5个就泄漏了
// 所以析构函数内部要做好try/catch,别让异常逃出去
try {
// 释放资源
} catch (...) {
// 吞掉异常或记录日志,但不往外抛
}
}
// C++98 风格:函数后面写 throw(可能抛的类型) void* operator new (size_t size) throw (std::bad_alloc); // 可能抛 bad_alloc void* operator delete (void* ptr) throw(); // 不抛异常 // 过于复杂,实践中没人用,C++11 废弃了
// C++11 简洁版 size_type size() const noexcept; // 承诺不抛异常 iterator begin() noexcept; // 承诺不抛异常
关键认知:
noexcept 修饰了函数,但里面调了 throw,编译器照样编译通过(顶多给个警告)noexcept 的函数如果真的抛了异常,程序会调用 std::terminate 终止noexcept——这样 STL 容器在做扩容等操作时才会优先用移动而非拷贝#includedouble 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
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++ exception 标准库参考
侠游戏发布此文仅为了传递信息,不代表侠游戏网站认同其观点或证实其描述