std::current_exception
来自 cppreference.cn
定义于头文件 <exception> |
||
std::exception_ptr current_exception() noexcept; |
(自 C++11 起) (constexpr 自 C++26 起) |
|
如果在异常处理期间(通常在 catch 子句中)调用,则捕获当前异常对象并创建一个 std::exception_ptr,该指针持有指向该异常对象的副本或引用(取决于实现)。只要存在引用它的 exception_ptr
对象,被引用的对象就保持有效。
如果此函数的实现需要调用 new 并且调用失败,则返回的指针将持有对 std::bad_alloc 实例的引用。
如果此函数的实现需要复制捕获的异常对象并且其复制构造函数抛出异常,则返回的指针将持有对抛出的异常的引用。如果抛出的异常对象的复制构造函数也抛出异常,则返回的指针可能持有对 std::bad_exception 实例的引用,以打破无限循环。
如果在未处理异常时调用该函数,则返回一个空的 std::exception_ptr。
可以在 std::terminate_handler 中调用此函数,以检索引发 std::terminate 调用的异常。
目录 |
[编辑] 返回值
一个 std::exception_ptr 实例,持有对异常对象、异常对象的副本、或对 std::bad_alloc 实例或 std::bad_exception 实例的引用。
[编辑] 注解
在遵循 Itanium C++ ABI (GCC、Clang 等) 的实现中,异常在抛出时在堆上分配(某些情况下 std::bad_alloc 除外),此函数仅创建引用先前分配的对象的智能指针。在 MSVC 上,异常在抛出时在栈上分配,此函数执行堆分配并复制异常对象。
在 Windows 托管 CLR 环境 [1] 中,当当前异常是托管异常时,实现将存储 std::bad_exception ([2])。请注意,catch(...) 也捕获托管异常
#include <exception> int main() { try { throw gcnew System::Exception("Managed exception"); } catch (...) { std::exception_ptr ex = std::current_exception(); try { std::rethrow_exception(ex); } catch (std::bad_exception const &) { // This will be printed. std::cout << "Bad exception" << std::endl; } } }
特性测试 宏 | 值 | 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) |
用于处理异常对象的共享指针类型 (typedef) |
(C++11) |
从 std::exception_ptr 抛出异常 (function) |
(C++11) |
从异常对象创建 std::exception_ptr (function template) |
(在 C++20* 中移除)(C++17) |
检查异常处理当前是否正在进行 (function) |