2011-07-18 15 views
6

如果我使用Boost期貨,並且未來會報告has_exception(),是否有任何方法可以檢索該異常?例如,下面是以下代碼:如何獲得報告boost :: future的異常?

int do_something() { 
    ... 
    throw some_exception(); 
    ... 
} 

... 

boost::packaged_task task(do_something); 
boost::unique_future<int> fi=task.get_future(); 
boost::thread thread(boost::move(task)); 
fi.wait(); 
if (fi.has_exception()) { 
    boost::rethrow_exception(?????); 
} 
... 

問題是,應該在什麼地方放置「?????」?

+0

文檔說的'has_exception':'真,如果*這與異步結果相關聯,這個結果是準備檢索,結果是一個存儲的異常'。但是,這一大堆的文檔沒有說明如何得到它...... – CharlesB

+0

你試過簡單的'fi.get()'? – Nim

回答

7

http://groups.google.com/group/boost-list/browse_thread/thread/1340bf8190eec9d9?fwc=2,你需要做的這個代替:

#include <boost/throw_exception.hpp> 

int do_something() { 
    ... 
    BOOST_THROW_EXCEPTION(some_exception()); 
    ... 
} 

... 
try 
{ 
    boost::packaged_task task(do_something); 
    boost::unique_future<int> fi=task.get_future(); 
    boost::thread thread(boost::move(task)); 
    int answer = fi.get(); 
} 
catch(const some_exception&) 
{ cout<< "caught some_exception" << endl;} 
catch(const std::exception& err) 
{/*....*/} 
... 
+0

謝謝。同時我找到了答案,查看源代碼。實際上,我發現它是以一種十分隱蔽的方式寫在文檔中的。 – petersohn