Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to react to an Exception raising to the top of the program without try/except in Python?

Can I catch and dump an exception (and the corresponding stacktrace) that would make the program crash without doing something like :

try:
   # whole program
except Execption as e:
   dump(e)
   raise

Sometime a external library crashes, and I'd like to react to Python dying and log the reasons it does so. I don't want to prevent the Exception from crashing the program, I just want the debug information.

Something like:

signals.register('dying', callback)

def callback(context):
    # dumping the exception and
    # stack trace from here

Is that even possible ?

like image 492
e-satis Avatar asked Mar 06 '13 11:03

e-satis


1 Answers

Yes, by registering a sys.excepthook() function:

import sys

def myexcepthook(type, value, tb):
    dump(type, value, tb)

sys.excepthook = myexcepthook

This replaces the default hook, which prints out the traceback to stderr. It is called whenever an uncaught exception is raised, and the interpreter is about to exit.

If you want to reuse the original exception hook from your custom hook, call sys.__excepthook__:

def myexcepthook(type, value, tb):
    dump(type, value, tb)
    sys.__excepthook__(type, value, tb)
like image 135
Martijn Pieters Avatar answered Oct 06 '22 10:10

Martijn Pieters