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(conststd::string& message ); | (C++11 前) | |
explicit failure(conststd::string& message, conststd::error_code& ec =std::io_errc::stream); | (C++11 起) | |
explicit failure(constchar* message, conststd::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
virtualconstchar* what()constthrow(); | (C++11 前) | |
virtualconstchar* what()constnoexcept; | (C++11 起) | |
返回解释字符串。
返回值
指向有由实现定义的解释信息的空终止字符串的指针。该字符串适合转换并显示为 std::wstring。保证该指针至少直到获得它来源的异常对象被销毁,或在该异常对象上调用非 const 成员函数(例如复制赋值运算符)为止一直有效。
返回的字符串在常量求值过程中按普通字面量编码。 | (C++26 起) |
注解
允许但不要求实现覆写 what()
。
继承自 std::system_error
成员函数
返回错误码 ( std::system_error 的公开成员函数) | |
[虚] | 返回解释性字符串 ( std::system_error 的虚公开成员函数) |
[编辑]注解
在解决 LWG 问题 331 前,std::ios_base::failure
有一个不带 throw() 的析构函数声明,但 std::exception::~exception() 的声明却带有 throw()[1]。这就意味着 std::ios_base::failure::~failure()
的异常声明更弱。解决方案是移除该声明,以保持不抛出的异常声明。
LWG 问题 363 针对的是同样的缺陷。它的解决方案是给 std::ios_base::failure::~failure()
的声明加上 throw()。该方案因为与前一个方案有冲突而没有被采纳。
[编辑]示例
#include <fstream>#include <iostream> int main(){std::ifstream f("不存在"); try{ f.exceptions(f.failbit);}catch(const std::ios_base::failure& e){std::cout<<"捕获了 ios_base::failure。\n"<<"解释字符串:"<< e.what()<<'\n'<<"错误码:"<< e.code()<<'\n';}}
可能的输出:
捕获了 ios_base::failure。 解释字符串:ios_base::clear: 未指定的 iostream_category 错误 错误码:iostream:1
[编辑]缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 48 | C++98 | 构造函数重载 (1) 以 msg 初始化基类 std::exception,但基类没有匹配的构造函数 | 删除相应描述 |
LWG 331 | C++98 | std::ios_base::failure 有一个不带 throw() 的析构函数声明 | 移除该析构函数声明 |
[编辑]参阅
(C++11) | 输入/输出流的错误码 (枚举) |