蓝色天空.知识 · 实践 · 创造
我的收藏
C++ 教程目录 99章
课程介绍
C++ / LEARN BY DOING

C++ <exception>

系统讲解 C++ 异常处理机制与 <exception> 头文件基础架构:throw/try/catch 语法、std::exception 基类与 what() 接口、自定义异常、常用标准异常类及 exception_ptr 跨边界传递。

学完这一章,你能够

  • 系统讲解 C++ 异常处理机制与 <exception> 头文件基础架构:throw/try/catch 语法、std::exception 基类与 what() 接口、自定义异常、常用标准异常类及 exception_ptr 跨边界传递。

C++ 异常处理模型与 <exception> 基础设施

异常处理是 C++ 中将错误检测与错误处理解耦的结构化机制,使程序在遭遇运行期故障时能够沿调用栈安全展开(自动触发局部 RAII 对象析构)并优雅恢复,而非直接崩溃。语言层面通过 `try`、`throw` 与 `catch` 关键字实现;标准库头文件 `<exception>` 提供所有标准异常的共同根基类 `std::exception` 以及 `std::bad_exception`、`std::exception_ptr`、`std::current_exception()`、`std::rethrow_exception()`、`std::terminate()` 等底层设施。

抛出异常使用 `throw exception_object;`(原则上可抛出任意可拷贝类型,但工程中几乎总是抛出派生自 `std::exception` 的对象)。捕获异常使用 `try { ... } catch (const std::exception& e) { ... }`——强烈推荐按 **`const` 引用**捕获,以避免按值捕获引发的对象切片(object slicing)与额外拷贝;若需兜底捕获非标准异常,可在最后放置通配块 `catch (...)`。

std::exception 基类、自定义异常与标准派生类

`std::exception` 声明了虚成员函数 `virtual const char* what() const noexcept;`,用于返回描述异常原因的 C 风格字符串。自定义异常类只需公有继承 `std::exception` 并重写 `what()` 即可被 `catch (const std::exception& e)` 多态捕获。需要说明的是,早期 C++98 代码中常见的 `const char* what() const throw()` 属于动态异常说明(已在 C++11 弃用并于 C++20 移除),现代 C++11 及以上应统一写作 `const char* what() const noexcept override`。

标准库围绕 `std::exception` 组织了清晰的异常层次(大部分派生类定义在 `<stdexcept>` 中,而 `std::bad_alloc` 位于 `<new>`、`std::bad_cast` 与 `std::bad_typeid` 位于 `<typeinfo>`):`std::logic_error` 家族(含 `std::invalid_argument`、`std::out_of_range` 等)对应编码期可预防的前置条件或逻辑缺陷;`std::runtime_error` 家族(含 `std::overflow_error`、`std::underflow_error` 等)对应仅在运行期暴露的外部环境或计算范围错误;`std::bad_alloc` 则由默认 `operator new` 在堆内存分配失败时抛出。

异常处理工程规范与注意事项

在工程实践中使用 `<exception>` 应遵守三条基本准则:首先,异常仅用于真正的异常错误路径,不得充当普通业务分支控制流;其次,虽然现代编译器大多采用“零开销异常表”策略使正常路径开销极低,但真正抛出与栈展开的成本仍显著高于返回值检查,热点循环内应避免高频抛异常;最后,务必在顶层边界确保各类异常得到妥善捕获或记录(配合 RAII 与 `noexcept` 析构函数),防止未捕获异常触发 `std::terminate()` 导致进程非正常中止。

实测 C++17 自定义 std::exception、标准异常家族、catch(...) 与 std::exception_ptr

含完整源码 · 137 行
展开查看收起
cpp
#include <cstdio>
#include <cstring>
#include <exception>
#include <iostream>
#include <new>
#include <stdexcept>
#include <string>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

} // namespace lab

namespace {

class MyException : public std::exception {
public:
    const char* what() const noexcept override {
        return "My custom exception";
    }
};

} // namespace

int main() {
    std::vector<lab::Case> cases;

    // Case 1: Custom exception derived from std::exception caught polymorphically
    std::string caught_msg;
    try {
        throw MyException();
    } catch (const std::exception& e) {
        caught_msg = e.what();
    }
    cases.push_back({
        "custom_exception_polymorphic_catch",
        lab::esc("My custom exception"),
        lab::esc(caught_msg),
        caught_msg == "My custom exception"
    });

    // Case 2: Standard exception hierarchy caught via const std::exception&
    int std_ok_count = 0;
    try { throw std::runtime_error("rt"); } catch (const std::exception& e) { if (std::string(e.what()) == "rt") ++std_ok_count; }
    try { throw std::logic_error("lg"); } catch (const std::exception& e) { if (std::string(e.what()) == "lg") ++std_ok_count; }
    try { throw std::invalid_argument("ia"); } catch (const std::exception& e) { if (std::string(e.what()) == "ia") ++std_ok_count; }
    try { throw std::out_of_range("oor"); } catch (const std::exception& e) { if (std::string(e.what()) == "oor") ++std_ok_count; }
    try { throw std::overflow_error("ov"); } catch (const std::exception& e) { if (std::string(e.what()) == "ov") ++std_ok_count; }
    try { throw std::underflow_error("un"); } catch (const std::exception& e) { if (std::string(e.what()) == "un") ++std_ok_count; }
    cases.push_back({
        "standard_exception_hierarchy",
        "6",
        std::to_string(std_ok_count),
        std_ok_count == 6
    });

    // Case 3: catch(...) and std::exception_ptr rethrow transport
    bool catch_all_ok = false;
    try {
        throw 404;
    } catch (const std::exception&) {
        catch_all_ok = false;
    } catch (...) {
        catch_all_ok = true;
    }
    std::exception_ptr eptr;
    try {
        throw std::runtime_error("transported");
    } catch (...) {
        eptr = std::current_exception();
    }
    std::string rethrown_msg;
    try {
        if (eptr) std::rethrow_exception(eptr);
    } catch (const std::exception& e) {
        rethrown_msg = e.what();
    }
    bool ptr_ok = catch_all_ok && (rethrown_msg == "transported");
    cases.push_back({"catch_all_and_exception_ptr", lab::jbool(true), lab::jbool(ptr_ok), ptr_ok});

    // Case 4: std::bad_alloc handling
    bool bad_alloc_ok = false;
    try {
        throw std::bad_alloc();
    } catch (const std::bad_alloc& e) {
        bad_alloc_ok = (std::strlen(e.what()) > 0);
    }
    cases.push_back({"bad_alloc_handling", lab::jbool(true), lab::jbool(bad_alloc_ok), bad_alloc_ok});

    lab::emit(cases);
    return 0;
}
验证 MyException 多态 what()、6 种标准异常捕获、catch(...) 兜底与 current_exception/rethrow_exception 转发以及 std::bad_alloc 处理。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2307.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2347.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

按值捕获 `std::exception e` 会触发对象切片(object slicing),丢失派生类的额外成员与虚表重写的 `what()` 信息;按 `const` 引用捕获既保留多态行为,又避免不必要的对象拷贝。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习