16

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!

Community
  • 1
  • 1
kynikos
  • 1,152
  • 4
  • 14
  • 25
  • For detailed differentiation between the various places that an exception can be raised from in a compound `with` statement, please see [this answer on the original question](https://stackoverflow.com/a/57280764/3767239). – a_guest Jul 30 '19 at 22:22
  • For me, I don't care whether the exception happens at init of the withable or when I'm using the withable, because it's a custom exception which ultimately gets handled the same way in either case. So actually the first example suits me best. – deed02392 Dec 10 '19 at 16:18

1 Answers1

20
try:
    f = open('foo.txt', 'a')
except IOError:
    print('error')
else:
    with f:
        #
        # some_code
        #
Pythoni
  • 304
  • 2
  • 2
  • 1
    You are perfectly right, I forgot to place 'with' under 'else'. – kynikos Mar 05 '11 at 18:35
  • Anyway my main question was if my guess was right: the answer given to the other older question was really worse than this method? – kynikos Mar 05 '11 at 18:43
  • Ok, I guess this is the best way to handle the exception in this case, so this is my accepted answer. Maybe you could copy this one also in the other question http://stackoverflow.com/questions/713794/catching-an-exception-while-using-a-python-with-statement – kynikos Mar 05 '11 at 20:00