std::promise<R>::set_exception
来自cppreference.com
void set_exception(std::exception_ptr p ); | (C++11 起) | |
自动存储异常指针 p 到共享状态中,并令状态就绪。
set_value、set_exception
、set_value_at_thread_exit 和 set_exception_at_thread_exit 的操作表现类似。在更新承诺体对象时获得与该承诺体对象关联的一个互斥体。
若无共享状态,或共享状态已存储值或异常,则抛出异常。
对此函数的调用和对 get_future 的调用之间不会造成数据竞争(因此它们不需要彼此同步)。
目录 |
[编辑]参数
p | - | 要存储的异常指针。若 p 为空则行为未定义 |
[编辑]返回值
(无)
[编辑]异常
遇到下列条件时为 std::future_error:
- *this 无共享状态。设置错误码为 no_state。
- 共享状态已存储值或异常。设置错误码为 promise_already_satisfied。
[编辑]示例
运行此代码
#include <future>#include <iostream>#include <thread> int main(){std::promise<int> p;std::future<int> f = p.get_future(); std::thread t([&p]{try{// 可能抛出的代码throwstd::runtime_error("Example");}catch(...){try{// 将抛出的任何异常存储到承诺体中 p.set_exception(std::current_exception());// 或代之以抛出一个自定义异常// p.set_exception(std::make_exception_ptr(MyException("mine")));}catch(...){}// set_exception() 亦可能抛出}}); try{std::cout<< f.get();}catch(conststd::exception& e){std::cout<<"来自线程的异常: "<< e.what()<<'\n';} t.join();}
输出:
来自线程的异常: Example
[编辑]参阅
设置结果为指示异常,同时仅在线程退出时分发提醒 (公开成员函数) |