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
#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 处理。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:06fc7e46aad663b8df7f853a9faa4fc876727fc5ff11364e678836dff8a3a62e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:09b723c18f0fa599d6de5216bc7dd3104b36004a690c901fcd990ed1f4a77a3d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么捕获标准异常时应写作 `catch (const std::exception& e)` 而不是 `catch (std::exception e)`?
展开参考解答
按值捕获 `std::exception e` 会触发对象切片(object slicing),丢失派生类的额外成员与虚表重写的 `what()` 信息;按 `const` 引用捕获既保留多态行为,又避免不必要的对象拷贝。