import logging
# 配置日志记录
logging.basicConfig(level=logging.INFO)
# 定义自定义异常类
class MyCustomError(Exception):
pass
# 定义上下文管理器
class FileReader:
def __init__(self, file_path):
self.file_path = file_path
def __enter__(self):
try:
self.file = open(self.file_path, 'r')
return self.file
except FileNotFoundError as e:
logging.error(f"文件未找到: {e}")
raise
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is MyCustomError:
logging.error(f"捕获到自定义异常: {exc_val}")
return True
elif exc_type is FileNotFoundError:
logging.error(f"文件未找到异常在 __exit__ 中再次捕获: {exc_val}")
return True
if self.file:
self.file.close()
# 使用上下文管理器
try:
with FileReader('nonexistent_file.txt') as file:
content = file.read()
if not content:
raise MyCustomError("文件内容为空")
except MyCustomError:
pass