这个建议看《c++高级编程》本书中的讲解,关于线程捕捉异常的问题,这里就不讲述了,直接上代码:
void doSomeWork()
{
for (int i=0; i<5;i++)
{
cout << i << endl;
}
cout << "Thread throwing a runtime_error exception ..." << endl;
throw runtime_error("Exception from thread");
}
void threadFunc(exception_ptr & err)
{
try
{
doSomeWork();
}
catch (const std::exception&)
{
cout << "Thread caught exception,returning exception..." << endl;
err = current_exception();
}
}
void doWorkInThread()
{
exception_ptr error;
// Launch background thread
thread t{threadFunc, ref(error)};
// wait for thread to finish
t.join();
//see if thread has thrown any exception
if (error)
{
cout << "Main thread receive exception, rethrowing it ...." << endl;
rethrow_exception(error);
}
else
{
cout << "Main thread did not receive any exception." << endl;
}
}
void testdoWorkInThread()
{
try
{
doWorkInThread();
}
catch (const std::exception& e)
{
cout << "Main function caught: '" <<e.what()<<" '" <<endl;
}
}
输出结果:
0
1
2
3
4
Thread throwing a runtime_error exception ...
Thread caught exception,returning exception...
Main thread receive exception, rethrowing it ....
Main function caught: 'Exception from thread '
这就是线程的捕捉异常,通常情况下不应该阻塞join,在GUI中,同过发送消息,来在界面显示。