有一个主线程,有一个子线程。主线程中调用子线程,并检查是否抛出异常,如果异常就处理异常信息。
主要思路:定义一个全局的std::exception_ptr对象,子线程抛异常时赋给该指针,主线程中检查该对象,然后处理对应的异常
//定义一个全局的异常指针,子线程中赋值,主线程中处理该异常
std::exception_ptr m_exp;
void worker(const std::string& msg)
{std::cout << msg << std::endl;//do some other workfor (int i = 0; i < 100; i++){if (i == 22){//子线程中抛出异常throw std::exception("raise an exception in worker thread");}}}int main()
{std::thread t1(worker, "恭喜发财");t1.join();if (m_exp){try{std::rethrow_exception(m_exp);}catch (const std::exception& ex){std::cout << ex.what() << std::endl;}}
}