std::current_exception
來自 cppreference.com
定義於標頭檔案 <exception> |
||
std::exception_ptr current_exception() noexcept; |
(C++11 起) (C++26 起為 constexpr) |
|
如果在異常處理期間(通常在 catch 子句中)呼叫,則捕獲當前異常物件並建立一個 std::exception_ptr,該物件包含該異常物件的副本或引用(取決於實現)。被引用物件至少在存在引用它的 exception_ptr
物件時保持有效。
如果此函式的實現需要呼叫 new 並且該呼叫失敗,則返回的指標將持有對 std::bad_alloc 例項的引用。
如果此函式的實現需要複製捕獲的異常物件並且其複製建構函式丟擲異常,則返回的指標將持有對所丟擲異常的引用。如果被丟擲異常物件的複製建構函式也丟擲異常,則返回的指標可能持有對 std::bad_exception 例項的引用,以中斷無限迴圈。
如果此函式在沒有異常被處理時呼叫,則返回一個空的 std::exception_ptr。
此函式可以在 std::terminate_handler 中呼叫,以檢索導致呼叫 std::terminate 的異常。
目錄 |
[編輯] 返回值
一個 std::exception_ptr 例項,持有對異常物件、異常物件副本、std::bad_alloc 例項或 std::bad_exception 例項的引用。
[編輯] 注意
在遵循 Itanium C++ ABI 的實現(GCC、Clang 等)上,異常在丟擲時分配在堆上(某些情況下 std::bad_alloc 除外),此函式只是建立引用先前分配物件的智慧指標。在 MSVC 上,異常在丟擲時分配在棧上,此函式執行堆分配並複製異常物件。
在託管 CLR 環境的 Windows 上 [1],噹噹前異常是託管異常時,實現將儲存一個 std::bad_exception ([2])。注意 catch(...) 也會捕獲託管異常。
#include <exception> int main() { try { throw gcnew System::Exception("Managed exception"); } catch (...) { std::exception_ptr ex = std::current_exception(); try { std::rethrow_exception(ex); } catch (std::bad_exception const &) { // This will be printed. std::cout << "Bad exception" << std::endl; } } }
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_constexpr_exceptions |
202411L |
(C++26) | 異常型別的 constexpr |
[編輯] 示例
執行此程式碼
#include <exception> #include <iostream> #include <stdexcept> #include <string> void handle_eptr(std::exception_ptr eptr) // passing by value is OK { try { if (eptr) std::rethrow_exception(eptr); } catch(const std::exception& e) { std::cout << "Caught exception: '" << e.what() << "'\n"; } } int main() { std::exception_ptr eptr; try { [[maybe_unused]] char ch = std::string().at(1); // this generates a std::out_of_range } catch(...) { eptr = std::current_exception(); // capture } handle_eptr(eptr); } // destructor for std::out_of_range called here, when the eptr is destructed
可能的輸出
Caught exception: 'basic_string::at: __n (which is 1) >= this->size() (which is 0)'
[編輯] 參閱
(C++11) |
用於處理異常物件的共享指標型別 (typedef) |
(C++11) |
從 std::exception_ptr 丟擲異常 (function) |
(C++11) |
從異常物件建立 std::exception_ptr (function template) |
(C++20 中移除*)(C++17) |
檢查當前是否正在進行異常處理 (function) |