python上下文 - 经理装饰器掩盖我的例外?

发布于 2025-02-11 22:20:44 字数 1138 浏览 1 评论 0 原文

按照 ..

在下面的合成代码中:

import sys
from contextlib import contextmanager, nullcontext


class MyException(Exception):

    def __init__(self, *args: object) -> None:
        super().__init__(*args)


@contextmanager
def annotate():
    try:
        yield None
    finally:
        return


def annotate2():
    return nullcontext()


def main():
    try:
        with annotate():
            raise MyException()

    except MyException:
        print("Good, Caught exception")
        sys.exit(0)

    print("How did I get here ???")
    sys.exit(1)


if __name__ == '__main__':
    main()

未捕获例外。 但是,如果我将其更改


 with annotate2():
            raise MyException()

为预期的。 我的问题是,我的上下文管理员怎么了?

@contextmanager
def annotate():
    try:
        yield None
    finally:
        return

(用Python 3.10.4测试)

谢谢

Boaz

Following the examples in https://docs.python.org/3/library/contextlib.html ..

In the synthetic code below:

import sys
from contextlib import contextmanager, nullcontext


class MyException(Exception):

    def __init__(self, *args: object) -> None:
        super().__init__(*args)


@contextmanager
def annotate():
    try:
        yield None
    finally:
        return


def annotate2():
    return nullcontext()


def main():
    try:
        with annotate():
            raise MyException()

    except MyException:
        print("Good, Caught exception")
        sys.exit(0)

    print("How did I get here ???")
    sys.exit(1)


if __name__ == '__main__':
    main()

The exception is not caught.
But if I change it to


 with annotate2():
            raise MyException()

Then it works as expected.
My question is, what is wrong with my contextmanager ?

@contextmanager
def annotate():
    try:
        yield None
    finally:
        return

(Tested with python 3.10.4)

Thanks

Boaz

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮生面具三千个 2025-02-18 22:20:44

谢谢,找到了答案
https://docs.python.org3/教程/errors.html#定义清洁 - 上的actions

如果最终子句执行休息,继续或返回语句,则不重新提高异常。

Thanks, found the answer in
https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions

If the finally clause executes a break, continue or return statement, exceptions are not re-raised.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文