Python thread exit code

Jiayao Yu picture Jiayao Yu · Jun 12, 2009 · Viewed 11.1k times · Source

Is there a way to tell if a thread has exited normally or because of an exception?

Answer

A. Coady picture A. Coady · Jun 12, 2009

As mentioned, a wrapper around the Thread class could catch that state. Here's an example.

>>> from threading import Thread
>>> class MyThread(Thread):
    def run(self):
        try:
            Thread.run(self)
        except Exception as err:
            self.err = err
            pass # or raise err
        else:
            self.err = None


>>> mt = MyThread(target=divmod, args=(3, 2))
>>> mt.start()
>>> mt.join()
>>> mt.err
>>> mt = MyThread(target=divmod, args=(3, 0))
>>> mt.start()
>>> mt.join()
>>> mt.err
ZeroDivisionError('integer division or modulo by zero',)