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 在更新 promise 物件時獲取與 promise 物件關聯的單個互斥量。
如果不存在共享狀態,或共享狀態已儲存值或異常,則丟擲異常。
此函式的呼叫不會與對 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 { // 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
[編輯] 參閱
將結果設定為指示異常,僅線上程退出時傳送通知 (公共成員函式) |