Python handles unchecked uncaptured exception instances, pythonunchecked

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.