【发布时间】:2022-01-22 12:11:41
【问题描述】:
假设我想在处理一个 txt 文件时引入一个 try-except 块。以下两种捕获可能异常的方式哪个是正确的?
try:
h = open(filename)
except:
h.close()
print('Could not read file')
try:
h = open(filename)
except:
print('Could not read file')
也就是说,即使发生异常,是否应该调用 h.close() ?
其次,假设你有如下代码
try:
h = open(filename)
"code line here1"
"code line here2"
except:
h.close()
print('Could not read file')
如果“code line here1”出现错误,我应该在except块中使用h.close()吗?
和前面的代码行有区别吗?
【问题讨论】:
-
最好的方法是使用
with open(filename) as h:打开文件。然后当程序流离开with块时它会自动关闭。而且你永远不应该使用空的except。指定要捕获的异常。