std::throw_with_nested
來自 cppreference.com
定義於標頭檔案 <exception> |
||
template< class T > [[noreturn]] void throw_with_nested( T&& t ); |
(C++11 起) (C++26 起為 constexpr) |
|
如果 std::decay<T>::type 是非 final 非 union 類型別,且既不是 std::nested_exception 也不是派生自 std::nested_exception,則丟擲未指定型別的異常,該異常公開派生自 std::nested_exception 和 std::decay<T>::type,並從 std::forward<T>(t) 構造。`nested_exception` 基類的預設建構函式呼叫 std::current_exception,如果存在,則將當前處理的異常物件捕獲到 std::exception_ptr 中。
否則,丟擲 std::forward<T>(t)。
要求 std::decay<T>::type 為 可複製構造的(CopyConstructible)。
目錄 |
[編輯] 引數
t | - | 要丟擲的異常物件 |
[編輯] 註解
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__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) |
用於捕獲和儲存當前異常的 mixin 型別 (類) |
(C++11) |
從 std::nested_exception 丟擲異常 (函式模板) |