名稱空間
變體
操作

std::promise<R>::set_exception

來自 cppreference.com
< cpp‎ | thread‎ | promise
 
 
併發支援庫
執行緒
(C++11)
(C++20)
this_thread 名稱空間
(C++11)
(C++11)
(C++11)
協同取消
互斥
(C++11)
通用鎖管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
條件變數
(C++11)
訊號量
門閂和屏障
(C++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危險指標
原子型別
(C++11)
(C++20)
原子型別的初始化
(C++11)(C++20 中已棄用)
(C++11)(C++20 中已棄用)
記憶體排序
(C++11)(C++26 中已棄用)
原子操作的自由函式
原子標誌的自由函式
 
 
void set_exception( std::exception_ptr p );
(C++11 起)

原子地將異常指標 p 儲存到共享狀態中,並使狀態就緒。

此操作的行為如同 set_value, set_exception, set_value_at_thread_exit, 和 set_exception_at_thread_exit 在更新 promise 物件時獲取與 promise 物件關聯的單個互斥量。

如果不存在共享狀態,或共享狀態已儲存值或異常,則丟擲異常。

此函式的呼叫不會與對 get_future 的呼叫引入資料競爭(因此它們之間不需要同步)。

目錄

[編輯] 引數

p - 要儲存的異常指標。如果 p 為空,則行為未定義。

[編輯] 返回值

(無)

[編輯] 異常

在以下條件下丟擲 std::future_error

  • *this 沒有共享狀態。錯誤碼被設定為 no_state

[編輯] 示例

#include <future>
#include <iostream>
#include <thread>
 
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());
                // or throw a custom exception instead
                // p.set_exception(std::make_exception_ptr(MyException("mine")));
            }
            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();
}

輸出

Exception from the thread: Example

[編輯] 參閱

將結果設定為指示異常,僅線上程退出時傳送通知
(公共成員函式) [編輯]