Talk is Cheap
Like Java, Python also provides for checked exception and unchecked exception. For checked exception, we usually use the try except to show the resolution, for the unchecked exception, but also provide a callback or a hook to help us deal with, we can record the crash stack trace in the hook or send crash data.
The following code implements the Python unchecked exception callback and outputs the log information.
Show Me the Code
Copy the Code code as follows:
#!/usr/bin/env python
# Coding=utf-8
Import OS, sys
Import logging
Logger = Logging.getlogger (__name__)
Handler = logging. Streamhandler (Stream=sys.stdout)
Logger.addhandler (Handler)
def handle_exception (Exc_type, Exc_value, Exc_traceback):
If Issubclass (Exc_type, Keyboardinterrupt):
Sys.__excepthook__ (Exc_type, Exc_value, Exc_traceback)
Return
Logger.error ("uncaught exception", exc_info= (Exc_type, Exc_value, Exc_traceback))
Sys.excepthook = Handle_exception
if __name__ = = "__main__":
Raise RuntimeError ("Test unhandled Exception")
Related explanations
1. The above ignore processing terminal under the keyboard press CTRL + C to terminate the exception.
2. The above uses the Python log management module to output formatted exception information.