如何将异常报告给boost::future

How to get the exception reported to boost::future?

本文关键字:boost future 报告 异常      更新时间:2023-10-16

如果我使用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(?????);
}
...

问题是,应该用什么来代替"?????"?

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