促进 ASIO 异常传播

Boost ASIO exception propagation

我注意到在许多 Boost ASIO 示例中,正在调用可能引发错误的函数,但没有使用 try/catch。例如,阻塞 UDP 客户端示例 here 具有以下功能:

  void check_deadline()
  {
    // Check whether the deadline has passed. We compare the deadline against
    // the current time since a new asynchronous operation may have moved the
    // deadline before this actor had a chance to run.
    if (deadline_.expires_at() <= deadline_timer::traits_type::now())
    {
      // The deadline has passed. The outstanding asynchronous operation needs
      // to be cancelled so that the blocked receive() function will return.
      //
      // Please note that cancel() has portability issues on some versions of
      // Microsoft Windows, and it may be necessary to use close() instead.
      // Consult the documentation for cancel() for further information.
      socket_.cancel();

      // There is no longer an active deadline. The expiry is set to positive
      // infinity so that the actor takes no action until a new deadline is set.
      deadline_.expires_at(boost::posix_time::pos_infin);
    }

    // Put the actor back to sleep.
    deadline_.async_wait(boost::bind(&client::check_deadline, this));
  }

deadline_.expires_at (here) 的文档指出此函数抛出 boost::system::system_error 异常。

在这个例子中没有捕捉到它是因为它只是一个例子,还是像这样的调用抛出的异常通过对 运行、运行-one 等的调用向上传播?换句话说,用 try catch 包装对 io_service.run() 的调用是否足以处理这些类型的异常?

此外,我还注意到 deadline_.async_wait 文档 here 声明处理程序需要引用 boost::system::system_error::error_code 的签名。我在 check_deadline() 函数中没有看到引用或占位符。

basic_deadline_timer::async_wait 文档状态:

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

这意味着处理程序将从内部调用 io_service::run()(在调用它的线程中),因此异常将自动传播到用户代码,并且 Asio 内部不需要特殊处理。为简单起见,通常示例不包括错误处理。

抱歉,我不知道为什么示例中没有指定 error_code 占位符。需要查看 Asio 资源。