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

std::promise::set_exception

void set_exception( std::exception_ptr p );

?

(since C++11)

原子存储异常指针。p进入共享状态并使状态就绪。

这个操作的行为就像set_value,,,set_exception,,,set_value_at_thread_exit,和set_exception_at_thread_exit在更新允诺对象时获取与承诺对象关联的单个互斥对象。

如果没有共享状态,或者共享状态已经存储了值或异常,则引发异常。

参数

p

-

exception pointer to store. The behavior is undefined if p is null.

返回值

%280%29

例外

std::future_error在下列条件下:

  • *this没有共享状态。错误类别设置为no_state...
  • 共享状态已存储值或异常。错误类别设置为promise_already_satisfied...

二次

代码语言:javascript
复制
#include <thread>
#include <iostream>
#include <future>
 
int main()
{
    std::promise<int> p;
    std::future<int> f = p.get_future();
 
    std::thread t([&p]{
        try {
            // code that may throw
            throw std::runtime_error("Example");
        } catch(...) {
            try {
                // store anything thrown in the promise
                p.set_exception(std::current_exception());
            } catch(...) {} // set_exception() may throw too
        }
    });
 
    try {
        std::cout << f.get();
    } catch(const std::exception& e) {
        std::cout << "Exception from the thread: " << e.what() << '\n';
    }
    t.join();
}

二次

产出:

二次

代码语言:javascript
复制
Exception from the thread: Example

二次

另见

set_exception_at_thread_exit

sets the result to indicate an exception while delivering the notification only at thread exit (public member function)

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

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

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com