当前位置: 代码网 > it编程>编程语言>C/C++ > C++异常处理完全指南(最新推荐)

C++异常处理完全指南(最新推荐)

2026年07月29日 C/C++ 我要评论
本文将详细讲解c++异常的抛出、捕获、栈展开、继承体系、重新抛出、异常安全、noexcept,最后手搓一个多模块项目的异常处理框架。一、为什么需要异常1.1 c语言的痛:错误码回想一下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;
}

关键语义

  1. throw 执行时,throw 后面的语句不再执行,函数立即退出
  2. 控制权从 throw 位置直接跳转到匹配的 catch
  3. 会生成异常对象的拷贝(因为局部对象在栈展开中会被销毁)

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匹配吗?匹配!→ 在这里处理

栈展开过程中会发生什么

  1. 从 throw 位置沿着调用链逐层退出
  2. 每退出一个函数,该函数内的局部对象都会被正确析构(这是 raii 的基础)
  3. 直到找到匹配的 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 → conststringconst string&权限缩小,安全
派生类 → 基类sqlexceptionexception&最实用!继承体系的基石
数组 → 指针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;                 // 承诺不抛异常

关键认知

  1. 编译器不强制检查——你用 noexcept 修饰了函数,但里面调了 throw,编译器照样编译通过(顶多给个警告)
  2. 运行时的处理——声明了 noexcept 的函数如果真的抛了异常,程序会调用 std::terminate 终止
  3. 移动构造/移动赋值尽量加 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++ exception 标准库参考

到此这篇关于c++异常处理完全指南的文章就介绍到这了,更多相关c++异常处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com