In Python processing unchecked an exception instance is not caught _python

Source: Internet
Author: User
Tags stack trace in python

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.

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.