Namespaces
Variants

std:: rethrow_exception

From cppreference.net
定义于头文件 <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 for exception types

示例

#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
void handle_eptr(std::exception_ptr eptr) // 按值传递是可接受的
{
    try
    {
        if (eptr)
            std::rethrow_exception(eptr);
    }
    catch(const std::exception& e)
    {
        std::cout << "捕获到异常: '" << 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);
} // 当 eptr 被销毁时,std::out_of_range 的析构函数在此处调用

可能的输出:

捕获到异常: 'basic_string::at: __n (which is 1) >= this->size() (which is 0)'

参阅

用于处理异常对象的共享指针类型
(typedef)
std::exception_ptr 中捕获当前异常
(function)