命名空间
变体
操作

std::rethrow_exception

来自 cppreference.cn
< 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) [编辑]