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模块
import
sys
try
:
a
=
b
b
=
c
except
:
info
=
sys.exc_info()
print
info[
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 traceback
try
:
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