Python handles unchecked uncaptured exception instances, pythonunchecked
Talk Is Cheap
Like Java, python also provides checked exception and unchecked exception. for checked exceptions, we usually use try again t to display and solve them. For unchecked exceptions, we also provide callbacks or hooks to help us handle them, we can record crash stack tracing or send crash data in the hook.
The following code implements the python unchecked exception callback and outputs log information.
Show Me The Code
Copy codeThe Code is 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. _ abstrthook _ (exc_type, exc_value, exc_traceback)
Return
Logger. error ("Uncaught exception", exc_info = (exc_type, exc_value, exc_traceback ))
Sys. policthook = handle_exception
If _ name _ = "_ main __":
Raise RuntimeError ("Test unhandled Exception ")
Explanations
1. The above ignores the handling terminal. Press Ctrl + C on the keyboard to terminate the exception.
2. The above uses the python log management module to output formatted exception information.