如何将异常报告为boost :: future?

时间:2011-07-18 09:00:05

标签: c++ exception boost-thread

如果我使用Boost期货,并且未来报告为has_exception(),是否有任何方法可以检索该异常?例如,以下是代码:

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(?????);
}
...

问题是,应该把什么放在“?????”?

1 个答案:

答案 0 :(得分:8)

根据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)
{/*....*/}
...