MST
星途 面试题库

面试题:Python中上下文管理器与异常处理的结合应用

请用Python实现一个上下文管理器,在进入上下文时打开一个文件,在退出上下文时关闭文件,并在文件读取过程中使用异常处理捕获可能出现的IOError异常,将错误信息打印出来。
47.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
class FileContextManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        try:
            self.file = open(self.filename, self.mode)
            return self.file
        except IOError as e:
            print(f"打开文件时出错: {e}")

    def __exit__(self, exc_type, exc_value, traceback):
        if self.file:
            self.file.close()
        if exc_type == IOError:
            print(f"读取文件时出错: {exc_value}")


# 使用示例
with FileContextManager('test.txt', 'r') as file:
    if file:
        try:
            content = file.read()
            print(content)
        except IOError as e:
            print(f"读取文件时出错: {e}")

上述代码定义了一个FileContextManager类作为上下文管理器,实现了打开和关闭文件,并在打开和读取文件过程中捕获IOError异常并打印错误信息。使用with语句调用该上下文管理器。