MST

星途 面试题库

面试题:Python自定义文件未找到异常及异常链处理

在Python中,设计一个自定义异常类,它继承自内置的`FileNotFoundError`,并在其中添加额外的属性(例如文件的预期用途等)。当在一个多层嵌套调用的函数结构中遇到文件未找到错误时,通过异常链的方式抛出并处理这个自定义异常,确保上层调用函数能够准确获取到完整的错误上下文信息,包括原始的文件未找到错误以及自定义添加的额外信息,同时要考虑如何在不丢失信息的前提下优雅地处理和传递异常。请提供完整的代码示例。
41.1万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
class CustomFileNotFoundError(FileNotFoundError):
    def __init__(self, file_path, expected_usage, *args, **kwargs):
        self.file_path = file_path
        self.expected_usage = expected_usage
        super().__init__(*args, **kwargs)


def inner_function():
    file_path = "nonexistent_file.txt"
    expected_usage = "read data for analysis"
    try:
        with open(file_path, 'r') as f:
            pass
    except FileNotFoundError as e:
        raise CustomFileNotFoundError(file_path, expected_usage) from e


def middle_function():
    try:
        inner_function()
    except CustomFileNotFoundError as e:
        raise


def outer_function():
    try:
        middle_function()
    except CustomFileNotFoundError as e:
        print(f"Custom File Not Found Error: {e}")
        print(f"File Path: {e.file_path}")
        print(f"Expected Usage: {e.expected_usage}")
        print(f"Original Error: {e.__cause__}")


if __name__ == "__main__":
    outer_function()