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

C++ 异常处理

系统介绍 C++ try/throw/catch 异常控制权转移机制、多分支与 catch(...) 兜底捕获、14 个标准异常层次族谱及继承 std::exception 自定义异常的现代写法。

学完这一章,你能够

  • 系统介绍 C++ try/throw/catch 异常控制权转移机制、多分支与 catch(...) 兜底捕获、14 个标准异常层次族谱及继承 std::exception 自定义异常的现代写法。

try / throw / catch 机制与多类型捕获

异常用于在运行时遇到非常规错误(如除数为零、下标越界或内存耗尽)时结构化地转移控制权。C++ 异常处理围绕三个关键字构建:`try` 包裹可能出错的保护代码块;`throw` 在出错位置抛出异常对象;紧随其后的一个或多个 `catch` 块按声明顺序匹配并处理对应类型的异常。

`throw` 可抛出任意可拷贝类型的表达式,捕获类型须与抛出类型相容(如除零函数抛出字符串字面量时,`catch` 需写成 `const char* msg`)。若需要兜底拦截未知类型异常,可在最后放置 `catch (...)`;实际工程中建议按 `const T&` 引用捕获以避免对象切片与额外拷贝。

标准异常层次体系与自定义异常类

C++ 标准库在 `<exception>` 与 `<stdexcept>` 中定义了以 `std::exception` 为根的完整异常继承树,向下分支涵盖内存/类型转换失败(`bad_alloc`、`bad_cast`、`bad_typeid`、`bad_exception`)、逻辑前置错误(`logic_error` 及其子类)以及运行期外部/算术错误(`runtime_error` 及其子类),全部 14 项说明见下表。

业务代码可通过公有继承 `std::exception`(或 `std::runtime_error`)并重写虚方法 `what()` 定义领域异常。注意早期 C++98 写法 `const char* what() const throw()` 在现代 C++11/17 中应写为 `const char* what() const noexcept override`(动态异常规范 `throw()` 已被弃用/移除);编写多个 `catch` 时应将更具体的派生异常写在基类 `const std::exception&` 之前。

C++ 标准异常层次结构速查

异常类触发场景与说明
std::exception所有标准 C++ 异常类型的公共基类,提供虚成员函数 what()。
std::bad_alloc默认版本运算符 new 动态分配内存失败时抛出。
std::bad_cast对引用执行 dynamic_cast 向下转型失败时抛出。
std::bad_typeid对多态类型的空指针解引用执行 typeid 时抛出。
std::bad_exception用于历史异常规范或异常传递机制中处理意外异常场景。
std::logic_error逻辑错误基类,通常对应可在调用前由代码逻辑规避的前置违约。
std::domain_error输入值落入数学函数有效定义域之外时抛出。
std::invalid_argument向函数传递无效参数时抛出(如 std::stoi 解析非法字符串)。
std::length_error试图构造或扩展超过容器最大允许长度(如 std::string)时抛出。
std::out_of_range带边界检查的访问越界时抛出(如 std::vector::at、std::bitset::test)。
std::runtime_error运行期错误基类,通常依赖运行环境或外部数据才能发现。
std::overflow_error数值运算发生上溢时报告的运行期异常。
std::range_error内部计算结果超出目标类型可表示范围时抛出。
std::underflow_error数值运算发生下溢时报告的运行期异常。

验证除零异常、多分支/catch(...) 匹配、标准异常族谱及自定义 std::exception 子类

含完整源码 · 112 行
展开查看收起
cpp
#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
#include <typeinfo>
#include <vector>

static double safe_division(int a, int b) {
    if (b == 0) {
        throw "Division by zero condition!";
    }
    return static_cast<double>(a) / static_cast<double>(b);
}

struct MyException : public std::exception {
    const char* what() const noexcept override {
        return "C++ Exception";
    }
};

struct PolyBase {
    virtual ~PolyBase() = default;
};

struct PolyDerived : public PolyBase {};

static std::string dispatch_catch(int mode) {
    try {
        if (mode == 1) throw 404;
        if (mode == 2) throw std::invalid_argument("bad_arg");
        throw 3.14;
    } catch (int code) {
        return "int:" + std::to_string(code);
    } catch (const std::invalid_argument& e) {
        return std::string("inv:") + e.what();
    } catch (...) {
        return "catch_all";
    }
}

int main() {
    // 1. Throw & catch const char* on divide-by-zero
    std::string div_err;
    double normal_val = safe_division(50, 5);
    try {
        (void)safe_division(50, 0);
    } catch (const char* msg) {
        div_err = msg;
    }
    std::string act1 = std::to_string(static_cast<int>(normal_val)) + "|" + div_err;
    const std::string exp1 = "10|Division by zero condition!";
    bool ok1 = (act1 == exp1);

    // 2. Multiple catch blocks & catch(...) fallback
    std::string act2 = dispatch_catch(1) + "," + dispatch_catch(2) + "," + dispatch_catch(3);
    const std::string exp2 = "int:404,inv:bad_arg,catch_all";
    bool ok2 = (act2 == exp2);

    // 3. Standard exception hierarchy (out_of_range, invalid_argument, bad_cast)
    int std_caught = 0;
    try {
        std::vector<int> v = {1, 2};
        (void)v.at(5);
    } catch (const std::out_of_range& e) {
        if (std::string(e.what()).size() > 0) ++std_caught;
    }
    try {
        (void)std::stoi("not_a_number");
    } catch (const std::invalid_argument&) {
        ++std_caught;
    }
    try {
        PolyBase base;
        (void)dynamic_cast<PolyDerived&>(base);
    } catch (const std::bad_cast&) {
        ++std_caught;
    }
    bool ok3 = (std_caught == 3);

    // 4. Custom exception inheriting std::exception & overriding what()
    std::string direct_msg;
    std::string poly_msg;
    try {
        throw MyException();
    } catch (const MyException& e) {
        direct_msg = e.what();
    }
    try {
        throw MyException();
    } catch (const std::exception& e) {
        poly_msg = e.what();
    }
    std::string act4 = direct_msg + "|" + poly_msg;
    const std::string exp4 = "C++ Exception|C++ Exception";
    bool ok4 = (act4 == exp4);

    std::cout << "{\n"
              << "  \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
              << "  \"cases\": [\n"
              << "    {\"name\": \"throw_catch_div_zero\", \"expected\": \"" << exp1
              << "\", \"actual\": \"" << act1 << "\", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
              << "    {\"name\": \"multi_catch_and_ellipsis\", \"expected\": \"" << exp2
              << "\", \"actual\": \"" << act2 << "\", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
              << "    {\"name\": \"std_exception_hierarchy\", \"expected\": 3, \"actual\": "
              << std_caught << ", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
              << "    {\"name\": \"custom_exception_what\", \"expected\": \"" << exp4
              << "\", \"actual\": \"" << act4 << "\", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
              << "  ]\n"
              << "}\n";
    return 0;
}
在 G++ 13.3.0 C++17 离线容器中验证 const char* 除零捕获、int/invalid_argument/catch(...) 分派、vector::at/stoi/dynamic_cast 三类标准异常及自定义 MyException 多态 what() 4 项全通过。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

因为 `catch` 子句按书写顺序自上而下匹配:派生类对象同样匹配基类引用,若把 `std::exception&` 写在前面,会提前截获所有派生异常,导致后面的具体子类处理器永远无法被执行。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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