Namespaces
Variants

std:: current_exception

From cppreference.net
定义于头文件 <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::bad_alloc 实例或 std::bad_exception 实例的 std::exception_ptr 实例。

注释

在遵循 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 &)
        {
            // 此处将被打印
            std::cout << "Bad exception" << std::endl;
        }
    }
}
功能测试 标准 功能
__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)
从异常对象创建 std::exception_ptr
(function template)
( C++20 中移除* ) (C++17)
检查当前是否正在进行异常处理
(function)