std::runtime_error
来自 cppreference.cn
定义于头文件 <stdexcept> |
||
class runtime_error; |
||
定义了要作为异常抛出的对象类型。它报告由程序范围之外且无法轻易预测的事件引起的错误。
继承关系图
以下标准库组件会抛出 std::runtime_error
类型的异常
(自 C++20) |
此外,以下标准异常类型派生自 std::runtime_error
(自 C++11) |
(自 C++17) |
(自 C++20) |
内容 |
[edit] 成员函数
(构造函数) |
用给定的消息构造新的 runtime_error 对象(公有成员函数) |
operator= |
替换 runtime_error 对象(公有成员函数) |
std::runtime_error::runtime_error
runtime_error( const std::string& what_arg ); |
(1) | |
runtime_error( const char* what_arg ); |
(2) | |
runtime_error( const runtime_error& other ); |
(3) | (noexcept since C++11) |
3) 复制构造函数。如果 *this 和 other 均具有动态类型
std::runtime_error
,则 std::strcmp(what(), other.what()) == 0。复制构造函数不得抛出异常。参数
what_arg | - | 解释性字符串 |
other | - | 要复制的另一异常对象 |
异常
1,2) 可能抛出 std::bad_alloc。
注解
由于复制 std::runtime_error
不允许抛出异常,故此消息典型地于内部存储为一块单独分配的引用计数字符串。这也是为何没有形参为 std::string&&
的构造函数:它无论如何都必须复制内容。
在 LWG 问题 254 获解决前,非复制构造函数仅能接受 std::string 。这使得为了构造 std::string 对象,动态分配成为强制性的。
在 LWG 问题 471 获解决后,导出的标准异常类必须拥有公开可访问的复制构造函数。只要 what()
取得的解释性字符串对于原对象和复制的对象相同,它就可以被隐式定义。
std::runtime_error::operator=
runtime_error& operator=( const runtime_error& other ); |
(noexcept since C++11) | |
以 other 的内容赋值内容。如果 *this 和 other 均具有动态类型 std::runtime_error
,则赋值后 std::strcmp(what(), other.what()) == 0。复制赋值运算符不得抛出异常。
参数
other | - | 要赋值的另一异常对象 |
返回值
*this
注解
在 LWG 问题 471 获解决后,导出的标准异常类必须拥有公开可访问的复制赋值运算符。只要 what()
取得的解释性字符串对于原对象和复制的对象相同,它就可以被隐式定义。
继承自 std::exception
成员函数
[virtual] |
销毁异常对象 ( std::exception 的虚公有成员函数) |
[virtual] |
返回解释性字符串 ( std::exception 的虚公有成员函数) |
[edit] 缺陷报告
下列行为变更缺陷报告被追溯地应用于先前发布的 C++ 标准。
DR | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 254 | C++98 | 接受 const char* 的构造函数缺失 | 已添加 |
LWG 471 | C++98 | std::runtime_error 的解释性字符串的副本是实现定义的 |
它们与 原始 std::runtime_error 对象相同 |