[issue1230540] sys.excepthook doesn't work in threads

STINNER Victor report at bugs.python.org
Sat May 25 19:15:19 EDT 2019


STINNER Victor <vstinner at redhat.com> added the comment:

> Indeed, if you write your own Thread class, you can add a try...except
> in the Thread.run() method.  You don't need a dedicated
> Thread.excepthook() method.

Exactly. You can already do you best in your run() method to handle exceptions.

threading.excepthook is only there is everything else already failed.

FYI in my implementation, if threading.excepthook raises a new exception, it's also handled... by sys.excepthook this time ;-)


> The only way a per-thread hook could be useful is if you could set it
> *outside* of the Thread class (so not as a method), so that one can e.g.
> catch / report exceptions raised in threads launches by third-party
> libraries.

I discuss threading excepthook with Pablo and he asked me if it would be possible to have a different behavior depending if the thread is spawn by my application or by "third party code". Using threading.excepthook, you can mark your threads that you spawn directly using a specific name, a special attribute, or you may even track them in a list (maybe using weak references).

If sys.excepthook is used to handle threading exceptions, you call threading.current_thread(), but then we come back to the issue to "dying" Python: exception which occurs late in Python finalization, when most modules are already cleared and import no longer works.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue1230540>
_______________________________________


More information about the Python-bugs-list mailing list