【问题标题】:How to catch throws not from your thread?如何捕捉不是来自线程的抛出?
【发布时间】:2026-01-07 08:10:01
【问题描述】:

假设我们有这样的伪代码:

super_local_thread()
{
try{
throw err;
}catch(err)
{
throw err2;
}

我们已经通过 boost 启动了该线程。 我们想用另一个线程来讨论它的错误。这种事情怎么办?

【问题讨论】:

  • 也许使用 std::async 捕获您的异常,然后您可以从 std::future 对象中提取异常。

标签: c++ linux multithreading boost error-handling


【解决方案1】:

C++11 指定了一个 current_exception 函数(在标准中,18.8 异常处理部分),让您可以做到这一点。

这是一篇关于 transporting exceptions between threads 的 MSDN 文章,它使用了这个功能。

由于您使用的是 Boost,因此这里是 current_exception 的 Boost 文档和 transporting exceptions between threads 上的 Boost 文章。

【讨论】:

    【解决方案2】:

    这篇 MSDN 文章可能有用

    http://msdn.microsoft.com/en-us/library/dd293602.aspx

    为了实现传输异常,Visual C++ 提供了 exception_ptr 类型和 current_exception、rethrow_exception 和 复制异常函数。

    【讨论】:

      【解决方案3】:

      你不能;异常只发生在单个线程上。不过,您可以让*函数捕获所有异常,并使用其他机制将异常报告给应用程序的其余部分。

      【讨论】: