Raise unhandled exceptions in a thread in the main thread? [duplicate]

二次信任 提交于 2019-12-03 06:12:32
Ned Batchelder

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

On your worker thread you do this (Python 2.x, see below for Python 3.x version):

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.

Python 3.x:

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

and on your main thread:

if self.exc_info:
    raise self.exc_info[1].with_traceback(self.exc_info[2])
return self.result
Alex Martelli

The only exception a secondary thread can reliably raise in the main thread is KeyboardInterrupt: the way the secondary thread does it is by calling the function thread.interrupt_main(). There is no way to associate extra info (about the reason for the exception) with the exception object that gets raised -- the latter's always just a plain KeyboardInterrupt. So, you need to stash that information away somewhere else, e.g. on a dedicated instance of Queue.Queue -- that info might include the results the secondary thread can get via sys.exc_info(), and anything else you find useful of course.

The main thread will need to recover that extra info (and take into account that the queue will be empty if the keyboard interrupt is actually due to the user hitting control-C or the like, so, use get_nowait and be ready to deal with a Queue.Empty exception, for example), format it however you desire, and terminate (if all secondary threads are daemons, the whole process terminates when the main thread terminates).

Christophe

Very unfortunately the accepted answer does not answer the question. You would rather pipe the exception details into a Queue. Please have a look at: Catch a thread's exception in the caller thread in Python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!