Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第六篇-上下文管理器改善异常处理流程的疑问 #50

Closed
douchen opened this issue Jul 14, 2020 · 1 comment
Closed

第六篇-上下文管理器改善异常处理流程的疑问 #50

douchen opened this issue Jul 14, 2020 · 1 comment

Comments

@douchen
Copy link

douchen commented Jul 14, 2020

class raise_api_error:
    """captures specified exception and raise ApiErrorCode instead

    :raises: AttributeError if code_name is not valid
    """
    def __init__(self, captures, code_name):
        self.captures = captures
        self.code = getattr(error_codes, code_name)

    def __enter__(self):
        # 该方法将在进入上下文时调用
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # 该方法将在退出上下文时调用
        # exc_type, exc_val, exc_tb 分别表示该上下文内抛出的
        # 异常类型、异常值、错误栈
        if exc_type is None:
            return False

        if exc_type == self.captures:
            raise self.code from exc_val
        return False

这里的 raise self.code from exc_val 是啥意思?from exc_val 没看懂。

@piglei
Copy link
Owner

piglei commented Jul 14, 2020

raise ... from ... 是链式抛出异常的语法,详见:https://stackoverflow.com/questions/24752395/python-raise-from-usage

在这里,self.code 是一个异常对象,exc_val 也是一个异常对象。raise self.code from exc_val 表示抛出 self.code 异常,但同时标明上级异常是 exc_val

@piglei piglei closed this as completed Jul 14, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants