在多线程 c++++ 中,异常处理通过 std::promise 和 std::future 机制实现:在抛出异常的线程中使用 promise 对象记录异常。在接收异常的线程中使用 future 对象检查异常。实战案例展示了如何使用 promise 和 future 在不同线程中捕获和处理异常。

如何处理跨线程的 C++ 异常
前言
在多线程编程中,异常可能会在任何线程中抛出。处理跨线程的异常需要额外的考虑,因为对于异常是如何以及在何处抛出的,没有明确的控制。
异常传递机制
C++ 标准库提供了一种传递异常的机制,称为 std::promise 和 std::future。我们可以使用它们来安全地在线程之间传递异常。
std::promise 负责生成异常,而 std::future 负责接收异常。两个对象必须在同一个线程中创建:
立即学习“C++免费学习笔记(深入)”;
睿拓智能网站系统-睿拓企业网站系统1.2免费版软件大小:6M运行环境:asp+access本版本是永州睿拓信息企业网站管理系统包括了企业网站常用的各种功能,带完整的后台管理系统,本程序无任何功能限制下载即可使用,具体功能如下。1.网站首页2.会员注册3.新闻文章模块4.产品图片展示模块5.人才招聘模块6.在线留言模块7.问卷调查模块8.联系我们模块9.在线QQ客服系统10.网站流量统计系统11.后
// 在主线程创建 std::promisepromise; std::future future = promise.get_future();
当异常在其他线程中抛出时,我们可以使用 promise 对象将其传递:
// 在 worker 线程
try {
// ... 代码可能会抛出异常
}
catch (const std::exception& e) {
promise.set_exception(std::make_exception_ptr(e));
}然后,可以在主线程中使用 future 对象来检查异常:
// 在主线程
try {
future.get();
}
catch (const std::exception& e) {
// 处理异常
}实战案例
以下代码展示了如何使用 std::promise 和 std::future 来处理跨线程异常:
#include#include #include // 打印函数以展示在不同线程中抛出的异常 void printFunction() { try { throw std::runtime_error("这是一个运行时错误!"); } catch (const std::exception& e) { std::cerr << "Worker 线程捕获异常:" << e.what() << '\n'; } } int main() { std::promise promise; std::future future = promise.get_future(); // 在新线程中运行打印函数 std::thread worker(printFunction); // 让主线程等待 worker 线程 try { future.get(); } catch (const std::exception& e) { std::cerr << "主线程捕获异常:" << e.what() << '\n'; } worker.join(); return 0; }
结论
通过使用 std::promise 和 std::future,我们可以安全地处理跨线程的异常。这使我们能够在异常发生后继续执行,并在以后处理它。









