In this article, we continue to learn Python exception handling , This paper mainly introduces try…except…finally Use of statements .
try…except The sentence can be in try Catch one or more exceptions in the branch and except Handle these exceptions in the branch . This statement also has an optional finally Branch :
try:
# Business code
except:
# exception handling
finally:
# Clean up the code
Whether or not there is an exception , It will be carried out finally Code in branch .try Branch or any except Execute immediately after branch execution finally Branch .
The following flowchart demonstrates try…except…finally Statement execution :
The following example uses try…except…finally sentence :
a = 10
b = 0
try:
c = a / b
print(c)
except ZeroDivisionError as error:
print(error)
finally:
print('Finishing up.')
The output is as follows :
division by zero
Finishing up.
In the example above ,try The branch produces a ZeroDivisionError abnormal , perform except The branch is followed by finally Branch .
In the following example try The branch did not generate an exception , So it's done try Branch and then execute finally Branch :
a = 10
b = 2
try:
c = a / b
print(c)
except ZeroDivisionError as error:
print(error)
finally:
print('Finishing up.')
The output is as follows :
5.0
Finishing up.
try…except…finally Statement except Branches can also be selected , So we can use :
try:
# Business code
finally:
# Code that will always be executed
Generally speaking , When we cannot handle exceptions but need to clean up resources, we can use this statement structure . for example , Whether there is an exception or not, you need to close the opened file .