Python 的上下文管理器协议对于资源管理至关重要。`__exit__` 方法的返回值可以控制异常的传播。根据以下代码,预测最终的输出结果是什么?
class ExceptionHandler:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print(f"Exiting context")
if isinstance(exc_value, IndexError):
print("IndexError suppressed.")
return True # 返回 True 表示抑制异常
return False # 返回 False 表示继续抛出异常
try:
with ExceptionHandler():
print("Inside 'with' block")
raise IndexError("Test index error")
print("Statement after 'with' block")
except IndexError:
print("IndexError caught outside.")
