Talk is Cheap
Like Java, Python also provides for checked exception and unchecked exception. For checked exception, we usually use a try except to show the solution, and for unchecked exceptions, it also provides a callback or a hook to help us deal with it, we can record the crash stack trace in the hook or send the crash data.
The following code implements the Python unchecked exception callback and outputs log information.
Show Me the Code
Copy 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 ignored processing terminal under the keyboard press CTRL + C to terminate the exception.
2. The above uses the Python log management module to output the formatted exception information.