下面的代碼是否提供正確的例外處理。我的目標是,除非檔案已成功打開并確保檔案已關閉,否則不要嘗試使用 file.write()。我不關心檔案未打開或檔案未寫入的確切錯誤。
Python 版本 3.6.9。作業系統 Linux。
data = "Some data"
filename = "test.txt"
try:
file = open(filename, 'w ')
except:
print("Error opening file")
else:
try:
file.write(data)
except:
print("Error writing to file")
finally:
file.close()
uj5u.com熱心網友回復:
您基本上不應該使用毯子except;始終說明您要處理的例外。
這是使用背景關系處理程式的重構,因此您可以避免顯式finally: close
data = "Some data"
filename = "test.txt"
try:
with open(filename, 'w ') as file:
try:
file.write(data)
except (IOError, OSError):
print("Error writing to file")
except (FileNotFoundError, PermissionError, OSError):
print("Error opening file")
您應該列舉更多的例外情況;我把這些從我的頭頂上嘎嘎作響。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458710.html
上一篇:系統未例外退出
