环境:
VS2019
包含头文件:
#include <iostream>
#include<thread>
#include<exception>
线程函数采用try{...}catch(...){...}机制
如果需要在主线程检测子线程的异常时,采用全局变量的方式获取
std::exception_ptr ptr;
void f0()
{
try {
std::string str;
for (int i = 0; i < 5; i++)
{
std::cout << "f0线程启动" << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
str.at(2); //越界访问
throw std::exception("线程中正常抛出异常"); //抛出异常
}
catch (const std::exception& m) {
std::cout <<"子线程输出异常信息:" << m.what() << std::endl;
ptr = std::current_exception();
}
}
int main()
{
std::thread t1(f0);
t1.join(); //主线程等待子线程结束
try {
if (ptr) {
std::cout << "检测到子线程异常" << std::endl;
std::rethrow_exception(ptr);
}
}
catch (std::exception& e)
{
std::cout <<"主线程输出子线程错误信息:" << e.what() << std::endl;
}
std::cout << "主线程退出!" << std::endl;
return 0;
}