2

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;
}
Karl Alexius
  • 313
  • 1
  • 6
  • 15
  • It all depends. Can you recover from it if it does? Also do you know how to catch exceptions? – NathanOliver Jun 12 '17 at 13:41
  • @NathanOliver in async settings, in particular, it is about knowing whether an exception in one of the many flows should stop the entire multiplexing service. In 90% of cases, that's not desired. Regular control flow does not apply in the proactor model – sehe Jun 12 '17 at 13:45

1 Answers1

8

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

sehe
  • 374,641
  • 47
  • 450
  • 633