首先,我们定义一个取数组中某个元素的函数。
def fetch(index):
a = [0, 1, 2, 3]
return a[index]
我们先来看看try和except之间的关系。
try:
fetch(4)
except:
print("index is out of range!")
只有try和except时,try无报错就只执行try,try报错则执行except。
下面我们来看看加入else之后的变化
try:
fetch(3)
except:
print("index is out of range!")
else:
print("index is within the range!")
在try和except的关系不变的情况下,当try执行的时候,else就会执行。
最后我们来看看finally的作用
try:
fetch(4)
except:
fetch(5)
finally:
print("all indices are out of range!")
我们可以看到,在try和except都报错的情况下,还是执行了finally。所以无论何种情况下,finally总会执行。