this is a continuation of question Catching an exception while using a Python 'with' statement.
I'm quite e newbie and I tested the following code with Python 3.2 on GNU/linux.
In the above-mentioned question, something similar to this was proposed to catch an exception from a 'with' statement:
try:
with open('foo.txt', 'a'):
#
# some_code
#
except IOError:
print('error')
That makes me wonder: what happens if some_code raises an IOError without catching it? It's obviously caught by the outer 'except' statement, but that could not be what I really wanted.
You could say ok, just wrap some_code with another try-except, and so on, but I know that exceptions can come from everywhere and it's impossible to protect every piece of code.
To sum up, I just want to print 'error' if and only if open('foo.txt', 'a') raises the exception, so I'm here to ask why the following code is not the standard suggested way of doing this:
try:
f = open('foo.txt', 'a')
except IOError:
print('error')
with f:
#
# some_code
#
#EDIT: 'else' statement is missing, see Pythoni's answer
Thank you!
try:
f = open('foo.txt', 'a')
except IOError:
print('error')
else:
with f:
#
# some_code
#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With