std::nested_exception
來自 cppreference.com
定義於標頭檔案 <exception> |
||
class nested_exception; |
(C++11 起) | |
std::nested_exception
是一個多型混合類,它可以捕獲並存儲當前異常,從而使得任意型別的異常可以相互巢狀。
|
(C++26 起) |
目錄 |
[編輯] 成員函式
構造一個巢狀異常 (公開成員函式) | |
[虛] |
析構一個巢狀異常 (虛公共成員函式) |
替換巢狀異常的內容 (公開成員函式) | |
丟擲儲存的異常 (公開成員函式) | |
獲取指向儲存異常的指標 (公開成員函式) |
[編輯] 非成員函式
(C++11) |
以混合了 std::nested_exception 的方式丟擲其引數 (函式模板) |
(C++11) |
從 std::nested_exception 丟擲異常 (函式模板) |
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_constexpr_exceptions |
202411L |
(C++26) | 異常型別的 constexpr |
[編輯] 示例
演示透過巢狀異常物件的構造和遞迴。
執行此程式碼
#include <exception> #include <fstream> #include <iostream> #include <stdexcept> #include <string> // prints the explanatory string of an exception. If the exception is nested, // recurses to print the explanatory string of the exception it holds void print_exception(const std::exception& e, int level = 0) { std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n'; try { std::rethrow_if_nested(e); } catch (const std::exception& nestedException) { print_exception(nestedException, level + 1); } catch (...) {} } // sample function that catches an exception and wraps it in a nested exception void open_file(const std::string& s) { try { std::ifstream file(s); file.exceptions(std::ios_base::failbit); } catch (...) { std::throw_with_nested(std::runtime_error("Couldn't open " + s)); } } // sample function that catches an exception and wraps it in a nested exception void run() { try { open_file("nonexistent.file"); } catch (...) { std::throw_with_nested(std::runtime_error("run() failed")); } } // runs the sample function above and prints the caught exception int main() { try { run(); } catch (const std::exception& e) { print_exception(e); } }
可能的輸出
exception: run() failed exception: Couldn't open nonexistent.file exception: basic_ios::clear
[編輯] 另請參閱
(C++11) |
用於處理異常物件的共享指標型別 (typedef) |
(C++11) |
以混合了 std::nested_exception 的方式丟擲其引數 (函式模板) |
(C++11) |
從 std::nested_exception 丟擲異常 (函式模板) |