2011-07-18 16 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