首页 > 试题广场 >

Python 的上下文管理器协议对于资源管理至关重要。`__

[单选题]
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.")
  • Entering context, Inside 'with' block, Exiting context, IndexError caught outside.
  • Entering context, Inside 'with' block, Exiting context, IndexError suppressed., IndexError caught outside.
  • Entering context, Inside 'with' block, Exiting context, IndexError suppressed., Statement after 'with' block
  • Entering context, Inside 'with' block, Exiting context
 with ExceptionHandler():执行后 进入__enter,然后执行with里面内容, raise IndexError("Test index error"),with块执行完然后执行__exit__(self, exc_type, exc_value, traceback):,if isinstance(exc_value, IndexError):为true, return True # 返回 True 表示抑制异常,然后继续执行  print("Statement after 'with' block"),没传播异常,所以 不执行
except IndexError:
    print("IndexError caught outside.")
发表于 今天 17:37:44 回复(0)