exception:發生在runtime時的error
要是沒有抓到錯誤,就會跑else的區塊,finally則是不管怎樣每次都會跑的區塊,在一般應用中例如可以把資料庫的關閉流程放在finally,這樣資料庫在這個程序中,只要執行完後,不管是否成功,都會去關閉它。
try:
with open('f.txt', 'r') as f:
for line in f:
x = int(line.strip())
except FileNotFoundError as e:
print('i caught an error:', e)
except ValueError as e:
print('could not convert to int', e)
else:
print('no exception caught')
finally:
print('in finally')