我不知道如何处理 python ‘with’ 语句的异常。如果我有代码:
with open("a.txt") as f:
print f.readlines()
我真的很想处理“文件未找到异常”以做某事。但我不会写
with open("a.txt") as f:
print f.readlines()
except:
print 'oops'
不能写
with open("a.txt") as f:
print f.readlines()
else:
print 'oops'
在 try/except 语句中包含 with
也不起作用,并且不会引发异常。我该怎么做才能以 Pythonic 方式处理 with
语句中的失败?
原文由 grigoryvp 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果你想对来自公开调用的错误和工作代码的错误进行不同的处理,你可以这样做: