std::current_exception
来自 cppreference.cn
定义于头文件 <exception> |
||
std::exception_ptr current_exception() noexcept; |
(C++11 起) (C++26 起为 constexpr) |
|
如果在异常处理期间(通常在 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 上,异常在抛出时分配在栈上,此函数执行堆分配并复制异常对象。
在托管 CLR 环境的 Windows 上 [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; } } }
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__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) |