MST

星途 面试题库

面试题:Python自定义异常与上下文管理器协同使用

定义一个自定义异常类`MyCustomError`,编写一个上下文管理器,在其`__enter__`方法中执行一个文件读取操作,在`__exit__`方法中捕获`MyCustomError`异常以及文件读取可能出现的`FileNotFoundError`异常,并在捕获异常时进行适当的日志记录(可以使用`logging`模块简单记录),最后展示如何使用这个上下文管理器。
14.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
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