std::invalid_argument
来自 cppreference.cn
定义于头文件 <stdexcept> |
||
class invalid_argument; |
||
定义一种作为异常抛出的对象类型。它报告由于参数值不被接受而产生的错误。
此异常由 std::bitset::bitset 以及 std::stoi 和 std::stof 函数家族抛出。
继承图
目录 |
[编辑] 成员函数
(构造函数) |
构造一个新的带给定消息的 invalid_argument 对象(公开成员函数) |
operator= |
替换 invalid_argument 对象(公开成员函数) |
std::invalid_argument::invalid_argument
invalid_argument( const std::string& what_arg ); |
(1) | |
invalid_argument( const char* what_arg ); |
(2) | |
invalid_argument( const invalid_argument& other ); |
(3) | (C++11 起无异常抛出) |
3) 复制构造函数。如果 *this 和 other 都具有动态类型
std::invalid_argument
,则 std::strcmp(what(), other.what()) == 0。复制构造函数不能抛出异常。参数
what_arg | - | 解释性字符串 |
其他 | - | 要拷贝的另一个异常对象 |
异常
1,2) 可能抛出 std::bad_alloc。
注意
因为复制 std::invalid_argument
不允许抛出异常,所以此消息通常在内部作为单独分配的引用计数字符串存储。这也是为什么没有接受 std::string&&
的构造函数:无论如何它都必须复制内容。
在 LWG issue 254 解决之前,非复制构造函数只能接受 std::string。它使得动态分配成为强制性,以便构造 std::string 对象。
在 LWG issue 471 解决之后,派生标准异常类必须具有公开可访问的复制构造函数。只要通过 what()
获取的解释性字符串对于原始对象和复制对象相同,就可以隐式定义它。
std::invalid_argument::operator=
invalid_argument& operator=( const invalid_argument& other ); |
(C++11 起无异常抛出) | |
用 other 的内容赋值。如果 *this 和 other 都具有动态类型 std::invalid_argument
,则赋值后 std::strcmp(what(), other.what()) == 0。复制赋值运算符不能抛出异常。
参数
其他 | - | 用于赋值的另一个异常对象 |
返回值
*this
注意
在 LWG issue 471 解决之后,派生标准异常类必须具有公开可访问的复制赋值运算符。只要通过 what()
获取的解释性字符串对于原始对象和复制对象相同,就可以隐式定义它。
继承自 std::logic_error
继承自 std::exception
成员函数
[virtual] |
销毁异常对象 ( std::exception 的虚公共成员函数) |
[virtual] |
返回解释字符串 ( std::exception 的虚公共成员函数) |
[编辑] 注释
此异常类型的目的类似于错误条件 std::errc::invalid_argument(由 std::thread 的成员函数在 std::system_error 中抛出)和相关的 errno 常量 EINVAL。
[编辑] 示例
运行此代码
#include <bitset> #include <iostream> #include <stdexcept> #include <string> int main() { try { std::bitset<4>{"012"}; // Throws: only '0' or '1' expected } catch (std::invalid_argument const& ex) { std::cout << "#1: " << ex.what() << '\n'; } try { [[maybe_unused]] int f = std::stoi("ABBA"); // Throws: no conversion } catch (std::invalid_argument const& ex) { std::cout << "#2: " << ex.what() << '\n'; } try { [[maybe_unused]] float f = std::stof("(3.14)"); // Throws: no conversion } catch (std::invalid_argument const& ex) { std::cout << "#3: " << ex.what() << '\n'; } }
可能的输出
#1: bitset string ctor has invalid argument #2: stoi: no conversion #3: stof: no conversion
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 254 | C++98 | 缺少接受 const char* 的构造函数 | 已添加 |
LWG 471 | C++98 | std::invalid_argument 的解释性字符串解释性字符串是实现定义的 |
它们与原始 std::runtime_error 对象的原始的 std::invalid_argument 对象 |