Python Gotcha: Logging an uncaught exception
I would be try/except blocks throughout my code but I would have a large try/except block to catch any uncaught exception. Andrew’s article did a good job showing me another way.
The solution is sys.excepthook. This is called when any exception is raised and uncaught, except for SystemExit. It’s pretty easy to utilize as well. A few small changes to the above code will allow us to log this completely unexpected ZeroDivisionError.
| |
The important bit is the new handle_uncaught_exception function and the
sys.excepthook line (with appropriate import statement).
What I would do with my code, especially the ones where I log using my log_to_db library, I will save to a database:
| |