Three common methods of the try except handler exception in Python

Source: Internet
Author: User

 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: Try: Statement 1 Statement 2 ...

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:

12345678 try :      statement 1      statement 2                 statement n except   ...:      do something ...

But you don't know what kind of exception "statement 1 to Statement n" is going to do, but you have to do exception handling, and you want to print out the exception and not stop the program, so how do you write the phrase "except ..."?

A summary of the 3 methods :

Method One: Catch all exceptions

12345 try :  &NBSP,      a Code class= "python keyword" >= b        b = c   except   exception,e:        print  exception, ,e

Method Two: Use the Traceback module to view exceptions

1234567 #引入python中的traceback模块, tracking error import  traceback   try :         a = b        b = c   except :        traceback.print_exc ()

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

12345678 #引入sys模块importsys  try:      a=b      b=c  except:      info=sys.exc_info()      printinfo[0],":",info[1]

However, if you want to save these exceptions to a log file to analyze these exceptions, consider the following:

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

123456789 import tracebacktry:      a=b      b=c  except:      f=open("c:log.txt",‘a‘)      traceback.print_exc(file=f)      f.flush()      f.close()

Three common methods of the try except handler exception in Python

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.