Search code examples
pythonmultithreadingexit-code

Python thread exit code


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


Solution

  • 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',)