std::overflow_error
定义于头文件 <stdexcept> |
||
class overflow_error; |
||
定义了作为异常抛出的对象类型。它可以用于报告算术溢出错误(即计算结果对于目标类型而言过大的情况)。
唯一抛出此异常的标准库组件是 std::bitset::to_ulong。 |
(直到 C++11) |
唯一抛出此异常的标准库组件是 std::bitset::to_ulong 和 std::bitset::to_ullong。 |
(自 C++11 起) |
标准库组件的数学函数不会抛出此异常(数学函数按照 math_errhandling 中的规定报告溢出错误)。然而,第三方库会使用它。例如,如果 boost::math::policies::throw_on_error
被启用(默认设置),boost.math 会抛出 std::overflow_error
。
继承关系图
目录 |
[编辑] 成员函数
(构造函数) |
使用给定消息构造一个新的 overflow_error 对象(公共成员函数) |
operator= |
替换 overflow_error 对象(公共成员函数) |
std::overflow_error::overflow_error
overflow_error( const std::string& what_arg ); |
(1) | |
overflow_error( const char* what_arg ); |
(2) | |
overflow_error( const overflow_error& other ); |
(3) | (noexcept 自 C++11 起) |
std::overflow_error
,则 std::strcmp(what(), other.what()) == 0。复制构造函数不会抛出异常。参数
what_arg | - | 解释性字符串 |
other | - | 要复制的另一个异常对象 |
异常
注解
由于复制 std::overflow_error
不允许抛出异常,因此此消息通常在内部存储为单独分配的引用计数字符串。这也是为什么没有接受 std::string&&
的构造函数的原因:无论如何它都必须复制内容。
在 LWG issue 254 的问题解决之前,非复制构造函数只能接受 std::string。这使得动态分配成为构造 std::string 对象的强制要求。
在 LWG issue 471 的问题解决之后,派生的标准异常类必须具有公开可访问的复制构造函数。只要通过 what()
获得的解释性字符串对于原始对象和复制对象相同,就可以隐式定义它。
std::overflow_error::operator=
overflow_error& operator=( const overflow_error& other ); |
(noexcept 自 C++11 起) | |
将内容赋值为 other 的内容。如果 *this 和 other 都具有动态类型 std::overflow_error
,则赋值后 std::strcmp(what(), other.what()) == 0。复制赋值运算符不会抛出异常。
参数
other | - | 要赋值的另一个异常对象 |
返回值
*this
注解
在 LWG issue 471 的问题解决之后,派生的标准异常类必须具有公开可访问的复制赋值运算符。只要通过 what()
获得的解释性字符串对于原始对象和复制对象相同,就可以隐式定义它。
继承自 std::exception
成员函数
[虚函数] |
销毁异常对象 (std::exception 的虚公共成员函数) |
[虚函数] |
返回解释性字符串 (std::exception 的虚公共成员函数) |
[编辑] 示例
#include <iostream> #include <limits> #include <stdexcept> #include <utility> template<typename T, int N> requires (N > 0) /*...*/ class Stack { int top_{-1}; T data_[N]; public: [[nodiscard]] bool empty() const { return top_ == -1; } void push(T x) { if (top_ == N - 1) throw std::overflow_error("Stack overflow!"); data_[++top_] = std::move(x); } void pop() { if (empty()) throw std::underflow_error("Stack underflow!"); --top_; } T const& top() const { if (empty()) throw std::overflow_error("Stack is empty!"); return data_[top_]; } }; int main() { Stack<int, 4> st; try { [[maybe_unused]] auto x = st.top(); } catch (std::overflow_error const& ex) { std::cout << "1) Exception: " << ex.what() << '\n'; } st.push(1337); while (!st.empty()) st.pop(); try { st.pop(); } catch (std::underflow_error const& ex) { std::cout << "2) Exception: " << ex.what() << '\n'; } try { for (int i{}; i != 13; ++i) st.push(i); } catch (std::overflow_error const& ex) { std::cout << "3) Exception: " << ex.what() << '\n'; } }
输出
1) Exception: Stack is empty! 2) Exception: Stack underflow! 3) Exception: Stack overflow!
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 254 | C++98 | 缺少接受 const char* 的构造函数 |
已添加 |
LWG 471 | C++98 | std::overflow_error 的副本是实现定义的副本是实现定义的 |
它们与 原始 std::overflow_error 对象相同 |