std::promise::set_exception

void set_exception( std::exception_ptr p );
(C++11 起)

存储异常指针 p 到共享状态中,并令状态就绪。

set_valueset_exceptionset_value_at_thread_exitset_exception_at_thread_exit 的操作表现类似。在更新 promise 对象时获得单个与 promise 对象关联的互斥。

若无共享状态,或共享状态已存储值或异常,则抛出异常。

目录

参数

p - 要存储的异常指针。若 p 为空则行为未定义。

返回值

(无)

异常

遇到下列条件时为 std::future_error

示例

#include <thread>
#include <iostream>
#include <future>
 
int main()
{
    std::promise<int> p;
    std::future<int> f = p.get_future();
 
    std::thread t([&p]{
        try {
            // 可能抛出的代码
            throw std::runtime_error("Example");
        } catch(...) {
            try {
                // 存储任何抛出的异常于 promise
                p.set_exception(std::current_exception());
            } catch(...) {} // set_exception() 亦可能抛出
        }
    });
 
    try {
        std::cout << f.get();
    } catch(const std::exception& e) {
        std::cout << "Exception from the thread: " << e.what() << '\n';
    }
    t.join();
}

输出:

Exception from the thread: Example

参阅

设置结果为指示异常,同时仅在线程退出时分发提醒
(公开成员函数)

版本历史

  • (当前 | 先前 2017年9月25日 (一) 03:06Fruderica讨论 | 贡献. . (1,861字节) (-269). . (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:33P12bot讨论 | 贡献 . . (2,130字节) (-49). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 19:14P12bot讨论 | 贡献 . . (2,179字节) (+321). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:08P12讨论 | 贡献 . . (1,858字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,858字节) (+1,858). . (Translated from the English version using Google Translate)