std::rethrow_exception

從 cppreference.com
< cpp‎ | error
在標頭 <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) // 按值传递 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); // 生成一个 std::out_of_range
    }
    catch(...)
    {
        eptr = std::current_exception(); // 捕获
    }
 
    handle_eptr(eptr);
 
} // std::out_of_range 的析构函数调用于此,此时析构 ept

可能的輸出:

Caught exception: 'basic_string::at: __n (which is 1) >= this->size() (which is 0)'

[編輯] 參閱

處理異常對象的共享指針類型
(typedef) [編輯]
捕獲當前異常到 std::exception_ptr 之中
(函數) [編輯]