Python Exception Handling

Source: Internet
Author: User

A common method of using try to handle program exceptions in Python

If you encounter an exception when you write a Python program and want to do the following, you usually use try to handle the exception, assuming the following program:

    1. Try
    2. Statement 1
    3. Statement 2
    4. .
    5. Statement n
    6. Except .....:
    7. Print .....

If you do not know what the "statement 1 to Statement n" will do when the exception, but you have to do exception handling, and want to print out the exception, do not stop the program's operation, then the "except ..." How to write this sentence?

A summary of at least 3 methods:

Method One: Catch all exceptions

    1. Try
    2. a=b
    3. b=C
    4. Except Exception,e:
    5. Print Exception, ":", E

Method Two: Use the Traceback module to view exceptions

    1. Import Traceback
    2. Try
    3. a=b
    4. b=C
    5. Except
    6. Traceback.print_exc ()

Method Three: Using the SYS module to backtrack the last anomaly

    1. Import Sys
    2. Try
    3. a=b
    4. b=C
    5. Except
    6. info=sys.exc_info ()
    7. Print info[0], ":", info[1]

If you also want to save these exceptions to a log file to analyze these exceptions, use the following method:

Save the information printed on the screen to a text file by Traceback.print_exc ()

      1. Try
      2. a=b
      3. b=C
      4. Except
      5. f=Open ("C:log.txt", ' a ')
      6. Traceback.print_exc (Ffile=f)
      7. F.flush ()
      8. F.close ()

Python Exception Handling

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.