关于c++线程异常处理的一个问题



演示代码:

#include <exception>
#include <future>
#include <iostream>
#include <stdexcept>
#include <thread>
void func1() {
std::cout << "Hello func1n";
throw std::runtime_error("func1 error");
}
int main() {
try {
std::future<void> result1 = std::async(func1);
result1.get();
} catch (const std::exception &e) {
std::cerr << "Error caught: " <<e.what() << std::endl;
}
}

输出:

Hello func1
Error caught: func1 Error

似乎main函数可以从线程中捕获异常。但是基于这个问题答:主函数不应该能够捕捉线程异常。这让我很困惑。也许我误解了一些信息。谁能给点建议?提前谢谢。

首先,std::asyncstd::thread根本不是一回事。此外,std::async不需要在另一个线程中执行可调用对象,它取决于您使用的启动策略。
我建议你阅读有关std::async的文档。

但是无论哪种方式,任何抛出的异常都已经由std::async处理,并存储在通过返回的std::future可访问的共享状态中,这意味着异常,如果有的话,在调用std::future<T>::get()时被重新抛出(在您的情况下发生在主线程中)。

最新更新