std::ios_base::failure
定义于头文件 <ios> |
||
class failure; |
||
类 std::ios_base::failure
定义了一个异常对象,该对象在输入/输出库中的函数发生故障时抛出。
|
(自 C++17 起) |
继承关系图 |
(直到 C++11) |
继承关系图 |
(自 C++11 起) |
目录 |
[编辑] 成员函数
(构造函数) |
使用给定的消息构造一个新的 failure 对象(公共成员函数) |
operator= |
替换 failure 对象(公共成员函数) |
what |
返回解释性字符串 (公共成员函数) |
std::ios_base::failure::failure
(1) | ||
explicit failure( const std::string& message ); |
(直到 C++11) | |
explicit failure( const std::string& message, const std::error_code& ec = std::io_errc::stream ); |
(自 C++11 起) | |
explicit failure( const char* message, const std::error_code& ec = std::io_errc::stream ); |
(2) | (自 C++11 起) |
(3) | ||
failure( const failure& other ); |
(直到 C++11) | |
failure( const failure& other ) noexcept; |
(自 C++11 起) | |
std::ios_base::failure
,则 std::strcmp(what(), other.what()) == 0。(自 C++11 起)参数
message | - | 解释性字符串 |
ec | - | 用于标识故障具体原因的错误代码 |
other | - | 要复制的另一个 failure |
注释
由于不允许复制 std::ios_base::failure
抛出异常,因此此消息通常在内部存储为单独分配的引用计数字符串。 这也是为什么没有接受 std::string&& 的构造函数的原因:它无论如何都必须复制内容。
std::ios_base::failure::operator=
failure& operator=( const failure& other ); |
(直到 C++11) | |
failure& operator=( const failure& other ) noexcept; |
(自 C++11 起) | |
使用 other 的内容赋值内容。 如果 *this 和 other 都具有动态类型 std::ios_base::failure
,则赋值后 std::strcmp(what(), other.what()) == 0。(自 C++11 起)
参数
other | - | 要赋值的另一个异常对象 |
返回值
*this
std::ios_base::failure::what
virtual const char* what() const throw(); |
(直到 C++11) | |
virtual const char* what() const noexcept; |
(自 C++11 起) | |
返回解释性字符串。
返回值
指向实现定义的空终止字符串的指针,其中包含解释性信息。该字符串适用于转换为 std::wstring 并显示。指针保证至少在获取它的异常对象被销毁之前,或者在该异常对象上调用非 const 成员函数(例如,复制赋值运算符)之前有效。
返回的字符串在常量求值期间使用普通文字编码进行编码。 |
(自 C++26 起) |
注释
允许但不是必须实现 what()
的重写。
继承自 std::system_error
成员函数
返回错误代码 ( std::system_error 的公共成员函数) | |
[virtual] |
返回解释性字符串 ( std::system_error 的虚公共成员函数) |
继承自 std::exception
成员函数
[virtual] |
销毁异常对象 ( std::exception 的虚公共成员函数) |
[virtual] |
返回解释性字符串 ( std::exception 的虚公共成员函数) |
[编辑] 注释
在 LWG issue 331 解决之前,std::ios_base::failure
声明了一个没有 throw() 的析构函数,其中 std::exception::~exception() 使用 throw()[1] 声明。这意味着 std::ios_base::failure::~failure()
具有较弱的异常规范。 解决方案是删除该声明,以便保留非抛出异常规范。
LWG issue 363 针对相同的缺陷,其解决方案是在 std::ios_base::failure::~failure()
的声明中添加 throw()。 由于两个解决方案之间的冲突,该解决方案未被应用。
[编辑] 示例
#include <fstream> #include <iostream> int main() { std::ifstream f("doesn't exist"); try { f.exceptions(f.failbit); } catch (const std::ios_base::failure& e) { std::cout << "Caught an ios_base::failure.\n" << "Explanatory string: " << e.what() << '\n' << "Error code: " << e.code() << '\n'; } }
可能的输出
Caught an ios_base::failure. Explanatory string: ios_base::clear: unspecified iostream_category error Error code: iostream:1
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 48 | C++98 | 构造函数重载 (1) 使用 msg 初始化基类 std::exception 但基类没有匹配的构造函数 |
相应的 描述已删除 |
LWG 331 | C++98 | std::ios_base::failure 声明了一个没有 throw() 的析构函数 |
删除了析构函数声明 |
[编辑] 参见
(C++11) |
IO 流错误代码 (枚举) |