如果在生成 std::thread 后引发,则未捕获异常
Exception not caught if raised after spawning std::thread
我对异常的奇怪行为感到困惑,这些异常在生成另一个线程后被抛出在主线程中:
void thread_body(){
while(true) cout << "in thread" << endl;
}
int main(int argc, char** argv)
{
try{
auto t = std::thread( thread_body );
throw std::runtime_error("error!");
t.join();
} catch (const std::exception& e) {
cout << e.what() << endl;
}
}
输出为:
in thread in thread in thread terminate called without an active exception The program has unexpectedly finished.
如果我在生成这样的线程之前抛出:
throw std::runtime_error("error!");
auto t = std::thread( thread_body );
比正常捕获:
错误!
为什么在第一种情况下没有捕获异常?我应该怎么做才能以通常的方式捕捉它?
当抛出异常时,线程对象将被销毁。但是线程析构函数将在它仍然可连接时被调用。这会导致调用terminate
,因此永远不会调用异常处理程序。
此外,在没有正确同步的情况下从不同线程写入标准流不是一个好主意。
好的,经过一些研究,我找到了这个问题的解决方案。必须将线程包装到类中并创建其实例,而不是创建原始线程。在析构函数中,可以检查线程是否仍然可连接,并在可能的情况下执行操作以优雅地停止线程主体。在这种情况下,当抛出异常时,析构函数将在线程仍在运行时被调用,它将整理事情。
相关文章:
- 当类定义不可见时捕获异常
- 来自 Android 应用程序内部的 boost 类型的 boost::wrapexcept<boost::system::system_error> 的未捕获异常
- 如何通过 pybind11 从 python 中的C++中捕获异常?
- 信号后未捕获异常
- 捕获异常后如何退出程序执行
- C++ 捕获异常后进行清理的标准方法是什么?
- 使用模板类引发和捕获异常
- E/libc++abi:终止于类型为google::protobuf::FatalException的未捕获异常
- 如果在生成 std::thread 后引发,则未捕获异常
- C++ 未捕获异常,程序将终止并中止
- C++程序在第一次尝试时会给出垃圾,但如果它捕获异常并重试,则会给出适当的值
- 仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够
- 如何捕获 I/O 异常(确切地说是 I/O,而不是 std::exception)
- 为什么捕获异常播放允许尾括号
- throw() 函数应该总是在异常时展开堆栈并允许捕获异常还是必须调用 std::terminate ?
- 寻求与类型为 std::invalid_argument 的未捕获异常相关的运行时错误的建议: stoi:无转换
- 如何从调用函数中捕获异常
- 当用户在字符数组中输入整数值时捕获异常
- C++按值捕获异常时的示例是不好的
- 使用 -O2 或 -O3 标志编译时未捕获异常