On the problem of python with in exception

students, there is a question to ask, the with sentence in python can help open and close some things, for example, when using open, if you add try before the with statement, if there is an exception in the with statement, will with still close the program after you go to exception?

Dec.02,2021

try:
    with open('xxx') as fin:
        pass
except Exception:
    pass

what you want to ask is this kind of code, right?
so first of all, you need to understand that the essence of the context manager protocol is [try-finally structure]:

try:
    try:
        fin = open('xxx')
        pass
    finally:
        fin.close()
except Exception:
    pass

Let's understand the nature of finally: temporarily suppress the exception thrown in the try clause until the finale clause has been executed, and then re-throw it.
in the above code, if an exception occurs in the pass part of the inner try clause, it will be caught and handled by finally before entering the outer except clause.
so what is the pass part of this inner try clause? Is the statement in the with structure. So the with structure can be cleaned up smoothly in any case.

Menu