名稱空間
變體
操作

std::rethrow_exception

來自 cppreference.com
< cpp‎ | 錯誤
定義於標頭檔案 <exception>
[[noreturn]] void rethrow_exception( std::exception_ptr p );
(C++11 起)
(C++26 起為 constexpr)

丟擲由異常指標 p 指向的先前捕獲的異常物件,或該物件的一個副本。

是否建立副本是未指定的。如果建立副本,則其儲存空間以未指定的方式分配。

如果 p 為空,則行為未定義。

目錄

[編輯] 引數

p - 非空 std::exception_ptr

[編輯] 異常

如果未建立副本,則丟擲 p 指向的異常物件。

否則,如果實現成功複製了異常物件,則丟擲該異常物件的一個副本。

否則,如果分配或複製失敗,則分別丟擲 std::bad_alloc 或複製異常物件時丟擲的異常。

[編輯] 注意

P1675R2 之前,rethrow_exception 不允許複製異常物件,這在某些異常物件分配在棧上的平臺上是無法實現的。

特性測試 標準 特性
__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)'

[編輯] 參閱

用於處理異常物件的共享指標型別
(typedef) [編輯]
將當前異常捕獲到 std::exception_ptr
(function) [編輯]