首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::current_exception

Defined in header <exception>

std::exception_ptr current_exception();

(since C++11)

如果在异常处理%28期间调用,则在catch子句%29捕获当前异常对象并创建std::exception_ptr它根据实现%29保存对异常对象%28的副本或引用。引用的对象至少在exception_ptr对象引用它。

如果此函数的实现需要调用new调用失败时,返回的指针将保存对std::bad_alloc...

如果此函数的实现需要复制捕获的异常对象,并且其复制构造函数抛出异常,则返回的指针将保存对抛出的异常的引用。如果抛出的异常对象的复制构造函数也抛出,则返回的指针可能包含对std::bad_exception打破无尽的循环。

如果在不处理异常时调用该函数,则为空std::exception_ptr会被归还。

参数

%280%29

返回值

的实例std::exception_ptr保存对异常对象或异常对象的副本的引用,或保存对std::bad_alloc的实例std::bad_exception...

例外

noexcept规格:

noexcept

二次

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
 
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 {
        std::string().at(1); // this generates an 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

二次

产出:

二次

代码语言:javascript
复制
Caught exception "basic_string::at"

二次

另见

exception_ptr (C++11)

shared pointer type for handling exception objects (typedef)

rethrow_exception (C++11)

throws the exception from an std::exception_ptr (function)

make_exception_ptr (C++11)

creates an std::exception_ptr from an exception object (function template)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券