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

Can I catch and throw an exception (and the corresponding stack) that will cause the program to crash without doing something like:

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

Once an external library is broken, and I would like to respond to Python, die and write down the reasons why this happens. I don’t want an exception from a program crash, I just want debug information.

Something like:

 signals.register('dying', callback) def callback(context): # dumping the exception and # stack trace from here 

Is it possible?

+7
source share
1 answer

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

 import sys def myexcepthook(type, value, tb): dump(type, value, tb) sys.excepthook = myexcepthook 

This replaces the default hook, which outputs the trace to stderr . It is called whenever an uncaught exception occurs 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) 
+12
source

All Articles