目錄
try...except...finally 結構
try...except...finally 結構中,finally 塊無論是否發生異常都會被執行;通常用來釋放 try 塊中申請的資源。
#try...except...finally 結構簡單測試
try:
a = input("請輸入一個被除數:")
b = input("請輸入一個除數:")
c = float(a)/float(b)
except BaseException as e:
print(e)
else:
print(c)
finally:
print("我是 finally 中的語句,無論發生異常與否,都執行!")
print("程序結束!")
#【示例】讀取文件,finally 中保證關閉文件資源
try:
f = open("d:/a.txt",'r')
content = f.readline()
print(content)
except BaseException as e:
print("文件未找到")
finally:
try:
f.close()
except BaseException as e:
print("文件沒打開,不需要關閉")
輸出:
D:\wwwroot\pyiteam\venv\Scripts\python.exe D:/wwwroot/pyiteam/mypro_obj/mypy02.py
請輸入一個被除數:12
請輸入一個除數:2
6.0
我是 finally 中的語句,無論發生異常與否,都執行!
程序結束!
文件未找到
文件沒打開,不需要關閉
Process finished with exit code 0