是否可以使用它来实现以下目标? (使用“with”关键字)
在:
try:
raise Exception("hello")
except Exception as e:
print "GOT IT"
期望效果:
def safety():
try:
yield
except Exception as e:
print "GOT IT"
with safety():
raise Exception("hello")
它只是使代码更清晰。目前正在运行第二个代码段会出现错误:
Traceback (most recent call last):
File "testing.py", line 25, in <module>
with safety():
AttributeError: __exit__
答案 0 :(得分:7)
你太近了!
from contextlib import contextmanager
@contextmanager
def safety():
try:
yield
except Exception as e:
print "GOT IT"
with safety():
raise Exception("hello")