0

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

Boaz Nahum
  • 1,049
  • 8
  • 9
  • Yes, I found the answer in https://stackoverflow.com/questions/15225819/try-catch-finally-return-clarification – Boaz Nahum Jun 30 '22 at 12:06

1 Answers1

0

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.

Boaz Nahum
  • 1,049
  • 8
  • 9