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 | - | 錯誤碼,用於標識失敗的具體原因 |
其他 | - | 另一個要複製的 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 起)
引數
其他 | - | 用於賦值的另一個異常物件 |
返回值
*this
std::ios_base::failure::what
virtual const char* what() const throw(); |
(C++11 前) | |
virtual const char* what() const noexcept; |
(C++11 起) | |
返回解釋字串。
返回值
指向一個實現定義的以 null 結尾的字串,其中包含解釋資訊。該字串適合轉換為 std::wstring 並顯示。該指標保證在獲取它的異常物件被銷燬或在該異常物件上呼叫非常量成員函式(例如複製賦值運算子)之前一直有效。
在常量求值期間,返回的字串使用普通字面量編碼進行編碼。 |
(C++26 起) |
注意
允許但不要求實現重寫 what()
。
繼承自 std::system_error
成員函式
返回錯誤碼 ( std::system_error 的公共成員函式) | |
[虛擬函式] |
返回解釋字串 ( std::system_error 的虛公共成員函式) |
繼承自 std::exception
成員函式
[虛擬函式] |
銷燬異常物件 ( std::exception 的虛公共成員函式) |
[虛擬函式] |
返回解釋字串 ( 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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 48 | C++98 | 建構函式過載 (1) 初始化了基類 std::exception 使用 msg,但基類沒有匹配的建構函式 |
相應地 描述已移除 |
LWG 331 | C++98 | std::ios_base::failure 聲明瞭一個沒有 throw() 的解構函式 |
移除了解構函式宣告 |
[編輯] 另請參閱
(C++11) |
I/O 流錯誤碼 (列舉) |