Is the following code doing anything wrong with with
statement and exception handling of python3? If no, what is the correct way of writing my expected output?
from contextlib import contextmanager
@contextmanager
def test():
print("Hello")
yield
print("goodbye")
try:
with test():
print("inside test")
raise KeyError
except KeyError:
print("KeyError")
else:
print("else")
finally:
print("finally")
and the output is
Hello
inside test
KeyError
finally
and I expect the output is:
Hello
inside test
goodbye
KeyError
finally
which I believe other people write similarly in the hope that the file would be closed when an exception was raised during the processing of the file.
My python3 version is:
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609]