34人参与 • 2026-07-29 • C/C++
本文将详细讲解c++异常的抛出、捕获、栈展开、继承体系、重新抛出、异常安全、noexcept,最后手搓一个多模块项目的异常处理框架。
回想一下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 <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 块这是异常最体现威力的时候——错误可以跨越 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 <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;
};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 容器在做扩容等操作时才会优先用移动而非拷贝#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++异常处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论