環境:
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;
}