在处理回调函数时,通常的异常处理方式是什么?

What is the usual way of handling exceptions when dealing with callback functions?

本文关键字:异常处理 方式 是什么 回调 处理 函数      更新时间:2023-10-16

我有一个非阻塞函数(它立即返回),创建一个新线程来解析一些数据:

boost::any Parse() throw(ParseException) {
  // parse something
}
typedef void (*HandlerFunc)(boost::any result);
void ParseAsync(HandlerFunc handler) {
  Parser me(*this);
  in_new_thread {
    boost::any result = me.Parse();
    handler(result);
  }
}

问题是Parse可以抛出异常。通常c++处理这些异常的方法是什么?我应该以某种方式"移交"异常处理程序函数?

新的c++ 11标准支持许多简化线程编程的功能。

在你的例子中,最有趣的是std::futurestd::promise

注意std::promise::set_exception_*函数。它允许您在其原始线程之外引导异常(注意std::exception_ptr具有共享指针语义)。您可以使用std::current_exception()(在catch语句中)来获得所需的指针。

然后注意std::future::get函数:如果提取futurepromise有一个异常而不是一个值,那么它将抛出异常。

这是将异常从一个线程传递到另一个线程的机制。

上次我做了类似的事情,我使用了一个单独的回调函数,该函数接受std::exception const &进行异常处理。但是,您需要注意对象的生命周期。