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:
- Try
- Statement 1
- Statement 2
- .
- Statement n
- Except .....:
- 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
- Try
- a=b
- b=C
- Except Exception,e:
- Print Exception, ":", E
Method Two: Use the Traceback module to view exceptions
- Import Traceback
- Try
- a=b
- b=C
- Except
- Traceback.print_exc ()
Method Three: Using the SYS module to backtrack the last anomaly
- Import Sys
- Try
- a=b
- b=C
- Except
- info=sys.exc_info ()
- 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 ()
- Try
- a=b
- b=C
- Except
- f=Open ("C:log.txt", ' a ')
- Traceback.print_exc (Ffile=f)
- F.flush ()
- F.close ()
Python Exception Handling