Should the exception thrown by boost::asio::io_service::run() be caught?

前端 未结 1 1463
野趣味
野趣味 2020-12-07 04:40

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

相关标签:
1条回答
  • 2020-12-07 05:05

    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

    0 讨论(0)
提交回复
热议问题