std::rethrow_exception
来自 cppreference.cn
定义于头文件 <exception> |
||
[[noreturn]] void rethrow_exception( std::exception_ptr p ); |
(自 C++11 起) (constexpr 自 C++26 起) |
|
抛出之前捕获的异常对象(由异常指针 p 指向),或该对象的副本。
是否创建副本是未指定的。如果创建副本,则为其分配存储的方式也是未指定的。
如果 p 为空,则行为未定义。
内容 |
[编辑] 参数
p | - | 非空 std::exception_ptr |
[编辑] 异常
如果未创建副本,则为 p 指向的异常对象。
否则,如果实现成功复制了异常对象,则为该异常对象的副本。
否则,如果分配或复制失败,则分别为 std::bad_alloc 或复制异常对象时抛出的异常。
[编辑] 说明
在 P1675R2 之前,rethrow_exception
不允许复制异常对象,这在某些异常对象在堆栈上分配的平台上是无法实现的。
特性测试宏 | 值 | Std | 特性 |
---|---|---|---|
__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) |
用于处理异常对象的共享指针类型 (类型别名) |
(C++11) |
在 std::exception_ptr 中捕获当前异常 (函数) |