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) | (C++11 起无异常抛出) |
std::overflow_error
,则 std::strcmp(what(), other.what()) == 0。复制构造函数不能抛出异常。参数
what_arg | - | 解释性字符串 |
其他 | - | 要拷贝的另一个异常对象 |
异常
注意
因为不允许复制 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 ); |
(C++11 起无异常抛出) | |
将内容赋值为 other 的内容。如果 *this 和 other 都具有动态类型 std::overflow_error
,则赋值后 std::strcmp(what(), other.what()) == 0。复制赋值运算符不能抛出异常。
参数
其他 | - | 用于赋值的另一个异常对象 |
返回值
*this
注意
在 LWG issue 471 解决之后,派生的标准异常类必须具有公开可访问的复制赋值运算符。只要通过 what()
获取的解释性字符串对于原始对象和复制对象相同,就可以隐式定义它。
继承自 std::exception
成员函数
[virtual] |
销毁异常对象 ( std::exception 的虚公共成员函数) |
[virtual] |
返回解释字符串 ( 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++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 254 | C++98 | 缺少接受 const char* 的构造函数 | 已添加 |
LWG 471 | C++98 | std::overflow_error 的解释性字符串解释性字符串是实现定义的 |
它们与原始 std::runtime_error 对象的原始 std::overflow_error 对象 |