C++ <stdexcept>
系统梳理 <stdexcept> 定义的 std::logic_error 与 std::runtime_error 两大具体异常家族及其全部标准派生类,辨析各标准异常所属头文件,并演示自定义派生异常类的正确实现。
学完这一章,你能够
- 系统梳理 <stdexcept> 定义的 std::logic_error 与 std::runtime_error 两大具体异常家族及其全部标准派生类,辨析各标准异常所属头文件,并演示自定义派生异常类的正确实现。
<stdexcept> 定位、头文件归属与异常层次总览
`<stdexcept>` 是 C++ 标准库中专门定义常用标准异常类的头文件。在代码中只需 `#include <stdexcept>`,即可通过 `throw std::runtime_error("An error occurred");` 等语句抛出携带可读错误消息的标准异常对象,并在外层 `try-catch` 块中按基类或具体派生类精准捕获。
从整个 C++ 标准库异常体系看,根类 `std::exception` 与 `std::bad_exception` 定义于 `<exception>`,`std::bad_alloc` 定义于 `<new>`,`std::bad_cast` 与 `std::bad_typeid` 定义于 `<typeinfo>`;而 **`<stdexcept>` 实际定义的是两大核心分支共 9 个具体异常类**:其一是 `std::logic_error` 及其四个派生类 `std::domain_error`、`std::invalid_argument`、`std::length_error`、`std::out_of_range`;其二是 `std::runtime_error` 及其三个派生类 `std::range_error`、`std::overflow_error`、`std::underflow_error`。
logic_error 与 runtime_error 两大标准家族详解
在典型参数校验示例 `riskyFunction(int x)` 中,若检测到 `x < 0` 便抛出 `std::invalid_argument("Negative value not allowed")`,主函数通过 `catch (const std::invalid_argument& e)` 捕获并输出 `e.what()`。所有标准异常共同继承自 `std::exception`,因此亦可统一通过 `const std::exception&` 读取 `what()` 说明。
`std::logic_error` 派生自 `std::exception`,用于报告程序自身逻辑或调用方违背前置条件的错误。需要纠正一个常见误解:**`std::logic_error`(以及 `std::runtime_error`)本身是具体类而非纯虚抽象基类**,可以直接实例化并抛出,同时也可作为更细粒度异常的基类。其四个标准派生类分别为:`std::invalid_argument`(无效实参)、`std::domain_error`(数学或业务定义域越界)、`std::length_error`(超出容器或字符串允许的最大长度)以及 `std::out_of_range`(如 `std::vector::at()` 或 `std::string::at()` 下标越界)。
`std::runtime_error` 同样是直接派生自 `std::exception` 的具体类,用于表达超出代码静态检查能力、只有在运行期结合外部输入或计算状态才会触发的错误。其三个标准派生类分别为:`std::range_error`(计算结果超出有效值域范围)、`std::overflow_error`(算术上溢)以及 `std::underflow_error`(算术下溢)。
继承标准异常构建自定义业务异常
当标准异常的语义仍不足以区分特定业务错误时,最佳实践是公有继承 `std::runtime_error` 或 `std::logic_error`(例如 `class MyException : public std::runtime_error`,在构造函数中将 `std::string` 消息转发给基类构造函数),从而免费复用标准库线程安全、引用计数式的 `what()` 字符串存储,避免手动管理 `char*` 缓冲区带来的内存拷贝抛异常风险。
实测 <stdexcept> 全部 9 个标准异常类、继承关系、非抽象特性与自定义派生异常
展开查看收起
#include <cstdio>
#include <cstring>
#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
#include <type_traits>
#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 {
int riskyFunction(int x) {
if (x < 0) {
throw std::invalid_argument("Negative value not allowed");
}
return x * 2;
}
class CustomRuntimeError : public std::runtime_error {
public:
explicit CustomRuntimeError(const std::string& msg) : std::runtime_error(msg) {}
};
} // namespace
int main() {
std::vector<lab::Case> cases;
// Case 1: riskyFunction throws std::invalid_argument on negative input
std::string msg1;
int ok_val = riskyFunction(5);
try {
(void)riskyFunction(-1);
} catch (const std::invalid_argument& e) {
msg1 = e.what();
}
bool c1 = (ok_val == 10) && (msg1 == "Negative value not allowed");
cases.push_back({"risky_function_invalid_argument", lab::jbool(true), lab::jbool(c1), c1});
// Case 2: std::logic_error family (concrete base + 4 standard derived classes)
bool logic_traits =
std::is_base_of_v<std::exception, std::logic_error> &&
std::is_base_of_v<std::logic_error, std::invalid_argument> &&
std::is_base_of_v<std::logic_error, std::domain_error> &&
std::is_base_of_v<std::logic_error, std::length_error> &&
std::is_base_of_v<std::logic_error, std::out_of_range> &&
!std::is_abstract_v<std::logic_error>;
int logic_caught = 0;
try { throw std::logic_error("L"); } catch (const std::logic_error& e) { if (std::string(e.what()) == "L") ++logic_caught; }
try { throw std::invalid_argument("IA"); } catch (const std::logic_error& e) { if (std::string(e.what()) == "IA") ++logic_caught; }
try { throw std::domain_error("DE"); } catch (const std::logic_error& e) { if (std::string(e.what()) == "DE") ++logic_caught; }
try { throw std::length_error("LE"); } catch (const std::logic_error& e) { if (std::string(e.what()) == "LE") ++logic_caught; }
try { throw std::out_of_range("OR"); } catch (const std::logic_error& e) { if (std::string(e.what()) == "OR") ++logic_caught; }
bool c2 = logic_traits && (logic_caught == 5);
cases.push_back({"logic_error_family", lab::jbool(true), lab::jbool(c2), c2});
// Case 3: std::runtime_error family (concrete base + 3 standard derived classes)
bool rt_traits =
std::is_base_of_v<std::exception, std::runtime_error> &&
std::is_base_of_v<std::runtime_error, std::range_error> &&
std::is_base_of_v<std::runtime_error, std::overflow_error> &&
std::is_base_of_v<std::runtime_error, std::underflow_error> &&
!std::is_abstract_v<std::runtime_error>;
int rt_caught = 0;
try { throw std::runtime_error("R"); } catch (const std::runtime_error& e) { if (std::string(e.what()) == "R") ++rt_caught; }
try { throw std::range_error("RE"); } catch (const std::runtime_error& e) { if (std::string(e.what()) == "RE") ++rt_caught; }
try { throw std::overflow_error("OF"); } catch (const std::runtime_error& e) { if (std::string(e.what()) == "OF") ++rt_caught; }
try { throw std::underflow_error("UF"); } catch (const std::runtime_error& e) { if (std::string(e.what()) == "UF") ++rt_caught; }
bool c3 = rt_traits && (rt_caught == 4);
cases.push_back({"runtime_error_family", lab::jbool(true), lab::jbool(c3), c3});
// Case 4: Custom exception derived from std::runtime_error & base std::exception
std::string custom_msg;
bool base_ex_ok = false;
try {
throw std::exception();
} catch (const std::exception& e) {
base_ex_ok = (std::strlen(e.what()) > 0);
}
try {
throw CustomRuntimeError("My custom exception occurred");
} catch (const std::runtime_error& e) {
custom_msg = e.what();
}
bool c4 = base_ex_ok && (custom_msg == "My custom exception occurred");
cases.push_back({"custom_derived_runtime_error", lab::jbool(true), lab::jbool(c4), c4});
lab::emit(cases);
return 0;
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
二者都不是抽象基类,可以直接构造并抛出;语义上 `std::logic_error` 表示原则上可通过修正代码或前置条件检查避免的逻辑缺陷,而 `std::runtime_error` 表示依赖运行期环境或外部状态才能发现的错误。