在处理回调函数时,通常的异常处理方式是什么?
What is the usual way of handling exceptions when dealing with callback functions?
我有一个非阻塞函数(它立即返回),创建一个新线程来解析一些数据:
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::future
和std::promise
。
注意std::promise::set_exception_*
函数。它允许您在其原始线程之外引导异常(注意std::exception_ptr
具有共享指针语义)。您可以使用std::current_exception()
(在catch
语句中)来获得所需的指针。
然后注意std::future::get
函数:如果提取future
的promise
有一个异常而不是一个值,那么它将抛出异常。
这是将异常从一个线程传递到另一个线程的机制。
上次我做了类似的事情,我使用了一个单独的回调函数,该函数接受std::exception const &
进行异常处理。但是,您需要注意对象的生命周期。
相关文章:
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- 使用 stoi 功能进行异常处理
- 子系统中的异常处理:本机
- 与异常处理程序中的操作员<<不匹配
- 数组 C++ 上的异常处理程序
- 异常处理:如果用户输入不是三个特定字符之一
- C++ 异常处理错误输出
- 视觉 std::矢量无异常:警告 C4530:使用了C++异常处理程序,但未启用展开语义.指定 /EHsc
- C++交换机状态异常处理
- 在字符串类上的成员函数和out_of_range异常处理
- 奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来
- 执行视觉工作室异常处理模式
- 为什么隐式转换在异常处理中从派生到基?
- 跨平台套接字发送,Linux 上的缓冲区常量无效* Windows上的常量字符*,最佳处理方式
- C++执行期间的类成员函数错误/异常处理
- 在处理回调函数时,通常的异常处理方式是什么?
- 你能把一个异常继承层次结构包装到另一个吗?——或者,另一种干净的处理方式
- 如何处理必须以异常安全方式获取多个资源的构造函数