简体   繁体   中英

Can I raise an exception in `__exit__`?

Can I raise exceptions in the __exit__ method? If so, will this exception be propagated out of a with block?

Example:

class X:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        raise MyException()


with X() as x:
    pass

// What happens here? Is `MyException` propagated up the stack?

Exceptions that occur during execution of this method will replace any exception that occurred in the body of the with statement.

https://docs.python.org/3/library/stdtypes.html#contextmanager. exit

And we could see with-statement for more details. No matter whether SUITE throw exception or not, the exception raised by __exit__ always be throw out to the caller.

with EXPRESSION as TARGET:
    SUITE

is semantically equivalent to:

manager = (EXPRESSION)
enter = type(manager).__enter__
exit = type(manager).__exit__
value = enter(manager)
hit_except = False

try:
    TARGET = value
    SUITE
except:
    hit_except = True
    if not exit(manager, *sys.exc_info()):
        raise
finally:
    if not hit_except:
        exit(manager, None, None, None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM