Raise unhandled exceptions in a thread in the main thread?

Matt Joiner picture Matt Joiner · Dec 6, 2009 · Viewed 20.9k times · Source

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

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.

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.

What's the best way to go about this?

Answer

Ned Batchelder picture Ned Batchelder · Dec 6, 2009

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 3.x, see below for Python 2.x version):

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

Python 2.x:

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.