Is it possible to capture any traceback generated by a Python application?
<p>I've been searching google for a way to somehow capture any traceback generated by a Python application.</p>

<p>I'd like to send an email/slack/notification to myself if <em>any</em> error occurs which generates a traceback (instead of relying on users to report issues to me).</p>

<p>I still haven't found anything <a href="http://code.activestate.com/recipes/442459-email-pretty-tracebacks-to-yourself-or-someone-you/" rel="nofollow">which doesn't involve you doing a try/except</a>. But of course I can't put everything I do inside individual try/except clauses since I'm writing applications which launch a UI (PySide/PyQt4/PySide2/PyQt5) and could error on user interaction.</p>

<p>Is this possible, and if so how can I capture any traceback generated?</p>

<p>You can easily do it by creating custom <a href="https://docs.python.org/2/library/sys.html#sys.excepthook" rel="nofollow"><code>sys.excepthook</code></a>:</p>

<pre><code>import sys
import traceback


def report_exception(exc_type, exc_value, exc_tb):
    # just a placeholder, you may send an e-mail here
    print("Type", exc_type)
    print("Value", exc_value)
    print("Tb", ''.join(traceback.format_tb(exc_tb)))


def custom_excepthook(exc_type, exc_value, exc_tb):
    report_exception(exc_type, exc_value, exc_tb)
    sys.__excepthook__(exc_type, exc_value, exc_tb)  # run standard exception hook


sys.excepthook = custom_excepthook

raise RuntimeError("I want to report exception here...")
</code></pre>

<p>For pretty-printing traceback objects refer to <a href="https://docs.python.org/2/library/traceback.html" rel="nofollow">traceback</a> module. </p>

python