Python中的finally关键字
先决条件:异常处理, Python中的 try 和 except
在编程中,可能会出现当前方法在处理一些异常时结束的情况。但是该方法在终止之前可能需要一些额外的步骤,例如关闭文件或网络等。
因此,为了处理这些情况, Python提供了一个关键字finally
,它总是在try
和except
块之后执行。 finally
块总是在try 块正常终止后或 try 块由于某些异常终止后执行。
句法:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
finally:
# Some code .....(always executed)
重点——
- finally块总是在离开try语句后执行。如果某些异常没有被 except 块处理,它会在 finally 块执行后重新引发。
- finally块用于释放系统资源。
- 可以在try之后使用finally而不使用except块,但在这种情况下不会处理任何异常。
示例 #1:
# Python program to demonstrate finally
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
输出:
Can't divide by zero
This is always executed
示例 #2:
# Python program to demonstrate finally
try:
k = 5//1 # No exception raised
print(k)
# intends to handle zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
输出:
5
This is always executed
示例#3:
# Python program to demonstrate finally
# Exception is not handled
try:
k = 5//0 # exception raised
print(k)
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
输出:
This is always executed
运行时错误 –
Unhandled Exception
k=5//0 #No exception raised
ZeroDivisionError: integer division or modulo by zero
解释:
在上面的代码中,异常是由零生成整数除法或模数,未处理。执行finally块后重新引发异常。这表明无论是否处理异常,都会执行finally块。