2014-12-03 106 views
1

我去了this例如5A - 它涵盖的异常与升压处理ASIO 的例子的代码粘贴在这里从该链接为快速参考加速异常,并加速处理ASIO

boost::mutex global_stream_lock; 

void WorkerThread(boost::shared_ptr<boost::asio::io_service> io_service) 
{ 
    .... 

    try 
    { 
     io_service->run(); 
    } 
    catch(std::exception & ex) 
    { 
     .... 
    } 

} 

void RaiseAnException(boost::shared_ptr<boost::asio::io_service> io_service) 
{ 
    io_service->post(boost::bind(&RaiseAnException, io_service)); 

    throw(std::runtime_error("Oops!")); 
} 

int main(int argc, char * argv[]) 
{ 
    boost::shared_ptr<boost::asio::io_service> io_service(
     new boost::asio::io_service 
     ); 
    boost::shared_ptr<boost::asio::io_service::work> work(
     new boost::asio::io_service::work(*io_service) 
     ); 


    boost::thread_group worker_threads; 
    for(int x = 0; x < 2; ++x) 
    { 
     worker_threads.create_thread(boost::bind(&WorkerThread, io_service)); 
    } 

    io_service->post(boost::bind(&RaiseAnException, io_service)); 

    worker_threads.join_all(); 

    return 0; 
} 

我的问题是,为什么是不是在这里抓到的异常?为什么笔者所要做的都mechansims error codetry-catch

赶上这样

try 
     { 
      boost::system::error_code ec; 
      io_service->run(ec); 
      if(ec) 
      { 
       .... 
      } 
      break; 
     } 
     catch(std::exception & ex) 
     { 
      .... 
     } 

我也是不明白作者的意思异常为了进一步澄清再次,如果我们正在使用io_service为用户 工作,我们必须使用异常处理,如果工作可以生成 异常。如果我们仅使用io_service作为boost :: asio函数 ,那么我们可以使用异常处理或错误变量作为 要么。如果我们使用io_service同时执行boost :: asio 函数和用户工作,那么我们既可以使用两种方法,也可以只使用 异常处理方法,但如果 工作可以生成异常,则不仅可以使用错误变量。这应该是非常简单的 。

我将不胜感激,如果有人可以澄清这

回答

4

你引用的解释是有点误导。

其实,io_service传播,从完成处理逃避任何异常,所以它不会不管我们使用它的“用户工作”或“ASIO功能” - 在任何情况下,我们可能要处理异常从io_service::run逃逸(不仅是std::exception!)。 考虑下面的示例:

void my_handler(const error_code&) 
{ 
    // this exception will escape from io_service::run()! 
    throw 0; 
} 

void setup_timer() 
{ 
    deadline_timer_.expires_from_now(seconds(5)); 
    deadline_timer_.async_wait(my_handler); 
} 

io_service::run(error_code &ec)io_service::run()之间的区别是,后者故意抛出例外,如果ec意味着错误。从io_service.ipp引述:

std::size_t io_service::run() 
{ 
    boost::system::error_code ec; 
    std::size_t s = impl_.run(ec); 
    boost::asio::detail::throw_error(ec); 
    return s; 
} 

因此,底线是,这将是足够使用投掷过载(和,可选地,多个catch处理程序来的异常类型之间进行区分)。