我正在尝试理解 with
语句。我知道它应该替换 try
/except
block 。
现在假设我做这样的事情:
try:
name = "rubicon" / 2 # to raise an exception
except Exception as e:
print("No, not possible.")
finally:
print("OK, I caught you.")
如何用上下文管理器替换它?
最佳答案
with
并没有真正取代 try
/except
,而是 try
/最后
。不过,您可以让上下文管理器在异常情况下与非异常情况下做一些不同的事情:
class Mgr(object):
def __enter__(self): pass
def __exit__(self, ext, exv, trb):
if ext is not None: print "no not possible"
print "OK I caught you"
return True
with Mgr():
name='rubicon'/2 #to raise an exception
return True
部分是上下文管理器决定抑制异常的地方(就像您通过不在 except
子句中重新引发它所做的那样)。
关于python - 通过语句和上下文管理器了解 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3693771/