class Context:
def __init__(self, name):
self.name = name
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print exc_type
print exc_val
print exc_tb
print "exiting..........."
print ".............."
return True
with Context("a") as f:
raise Exception("dsdf")
print "test"
在with中 中抛出的异常会被__exit__捕捉, exc_type 是异常类型Excepton, exc_val 是异常值: dsdf, exc_tb 异常追踪
with中的异常不会使程序推出,可以正常执行 __exit__中函数