Python's try statement has two styles
One is to handle exceptions (try/except/else)
The second is that the final code will be executed regardless of whether an exception occurs (try/finally)
try/except/else style
try:<Statement#Running code
except<first name:
< Statement#If it is triggered in the try part'name'abnormal
except<first name,<data:<Statement#If it triggers'name'Exception, get additional data
else:<Statement#If no exception occurs
The working principle of try is that when a try statement is started, python marks it in the context of the current program, so that when an exception occurs, you can come back here. The try clause is executed first, and what happens next depends on the execution time. Whether there is an abnormality.
1、 If an exception occurs when the statement after the try is executed, python jumps back to the try and executes the first except clause that matches the exception. After the exception is processed, the control flow passes through the entire try statement (unless a new Exception).
2、 If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (this will end the program and print the default error message).
3、 If no exception occurs during the execution of the try clause, python will execute the statement after the else statement (if there is an else), and then control flow through the entire try statement.
try/finally style
try:<Statement
finally:<Statement#Always execute when exiting try
Python will always execute the finally clause, regardless of whether an exception occurs when the try clause is executed.
1、 If no exception occurs, python runs the try clause, then the finally clause, and then continues.
2、 If an exception occurs in the try clause, python will return to execute the finally clause, and then submit the exception to the upper try, and the control flow will not pass through the entire try statement.
Try/finally is useful when you want to ensure that certain code is executed regardless of whether an exception occurs.
This is useful when opening a file finally always close() the file at the end
**Try statement clause form **
try:
f=open('file.txt')
exceptIOError,e:
printe
else:
print'wrong'
[ Errno2]Nosuchfileordirectory:'file.txt'
The latest python version supports try/except/finally
1: If x is not abnormal, execute z, i
2: If x is abnormal:
One: if except catches an exception, execute y, i
Two: not caught, execute i, and then return to built-in exception handling
try:
x
except(name):
y
else:
z
finally:
i
Recommended Posts