std::thread 的构造函数有如下重载形式:
函数声明 |
---|
thread() noexcept; |
thread( thread&& other ) noexcept; |
template< class Function, class… Args > explicit thread( Function&& f, Args&&… args ); |
可以看到,前两个构造函数不会抛出异常,而最后一个则可能会抛出异常。
相关异常:
如果线程无法启动,则返回 std::system_error。异常可能表示错误条件std::errc::resource_unavailable_try_again 或其他特定于实现的错误条件。
处理异常:例子
#include <thread>
#include <iostream>
#include <system_error>
int main()
{
try {
std::thread().detach(); // attempt to detach a non-thread
}
catch(const std::system_error& e) {
std::cout << "Caught system_error with code " << e.code()
<< " meaning " << e.what() << '\n';
}
}