在主线程中的线程中提高未处理的异常? [英] Raise unhandled exceptions in a thread in the main thread?

查看:137
本文介绍了在主线程中的线程中提高未处理的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些类似的问题,但没有提供我需要的答案。

There are some similar questions, but none supply the answer I require.

如果我通过 threading.Thread ,然后抛出未处理的异常,那些线程被终止。我希望使用堆栈跟踪保留异常详细信息中的默认打印,但也可以减少整个过程。

If I create threads via threading.Thread, which then throw exceptions which are unhandled, those threads are terminated. I wish to retain the default print out of the exception details with the stack trace, but bring down the whole process as well.

我认为可能捕获线程中的所有异常,并在主线程对象上重新启动它们,也可能手动执行默认异常处理,然后在主线程上提出一个 SystemExit

I've considered that it might be possible to catch all exceptions in the threads, and reraise them on the main thread object, or perhaps it's possible to manually perform the default exception handling, and then raise a SystemExit on the main thread.

最好的方法是什么?

推荐答案

我写了关于在Python中重新抛出异常,包括非常像这样的例子。

I wrote about Re-throwing exceptions in Python, including something very much like this as an example.

在你的工作线程上,你这样做: / p>

On your worker thread you do this:

try:
    self.result = self.do_something_dangerous()
except Exception, e:
    import sys
    self.exc_info = sys.exc_info()

和你的主线程你这样做:

and on your main thread you do this:

if self.exc_info:
    raise self.exc_info[1], None, self.exc_info[2]
return self.result

异常会出现在主线程中,就好像它有在工作线程中被提出。

The exception will appear in the main thread just as if it had been raised in the worker thread.

这篇关于在主线程中的线程中提高未处理的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆