Common methods for handling program exceptions using try in python

Source: Internet
Author: User

If you want to handle the following exceptions when writing a python program, try is generally used to handle the exception. Suppose there is a program: try: Statement 1 Statement 2. statement N contains t .........: print ....... however, you do not know what exceptions will occur when running "Statement 1 to statement N", but you still need to handle the exceptions and want to print out the exceptions, does not stop the program running, so in "Running t ...... "How should I write this sentence? At least three methods are summarized: Method 1: Catch all exceptions try: a = B = c except t Exception, e: print Exception, ":", e try: a = B = c Release t Exception, e: print Exception, ":", e www.2cto.com Method 2: Use the traceback module to view the Exception import traceback try: a = B = c Release t: traceback. print_exc () import traceback try: a = B = c Release T: traceback. print_exc () method 3: Use the sys module to trace the last exception import sys try: a = B = c except: info = sys. exc_info () print info [0], ":", info [1] import sys try: a = B = c country T: info = sys. exc_info () print info [0], ":", info [1]. However, if you want to save these exceptions to a log file, take a look at the following method: Put traceback. print_exc (): Save the information printed on the screen to a text file. try: a = B = c character T: f = open ("c: log.txt", 'A ') traceback. print_exc (file = f) f. flush () f. close ()

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.