Should the exception thrown by boost::asio::io_ser

2020-02-02 01:16发布

问题:

boost::asio::io_service::run() throws a boost::system::system_error exception in case of error. Should I handle this exception? If so, how?

my main.cpp code is something like this:

main()
{
    boost::asio::io_service queue;
    boost::asio::io_service::work work(queue);
    {
      // set some handlers...
      **queue.run();**
    }
    // join some workers...
    return 0;
}

回答1:

Yes.

It is documented that exceptions thrown from completion handlers are propagated. So you need to handle them as appropriate for your application.

In many cases, this would be looping and repeating the run() until it exits without an error.

In our code base I have something like

static void m_asio_event_loop(boost::asio::io_service& svc, std::string name) {
    // http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.effect_of_exceptions_thrown_from_handlers
    for (;;) {
        try {
            svc.run();
            break; // exited normally
        } catch (std::exception const &e) {
            logger.log(LOG_ERR) << "[eventloop] An unexpected error occurred running " << name << " task: " << e.what();
        } catch (...) {
            logger.log(LOG_ERR) << "[eventloop] An unexpected error occurred running " << name << " task";
        }
    }
}

Here's the documentation link http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.effect_of_exceptions_thrown_from_handlers