Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Boost.Asio documentation suggests the following exception handling pattern:

boost::asio::io_service io_service;
...
for (;;)
{
  try
  {
    io_service.run();
    break; // run() exited normally
  }
  catch (my_exception& e)
  {
    // Deal with exception as appropriate.
  }
}

The problem with it is that the context of exception is lost at the point when it's handled. For example, if I have multiple socket sessions in a given io_service, I don't know which one caused the exception.

What would be a better way to handle the exceptions from asynchronous handlers without wrapping them in try/catch blocks?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
565 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is nothing wrong with the pattern recommended by Boost.Asio. What you should do is package any necessary information for handling the exception along with the exception object. If you use boost::exception (or a type derived from it) for your exception handling, you can very easily attach metadata (including session information) by creating a specialization of boost::error_info and attaching it to the exception object using operator<<. Your catch block can then extract this info with get_error_info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...