Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching an exception while using a Python 'with' statement - Part 2

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!

like image 421
kynikos Avatar asked Mar 05 '11 18:03

kynikos


1 Answers

try:
    f = open('foo.txt', 'a')
except IOError:
    print('error')
else:
    with f:
        #
        # some_code
        #
like image 165
Pythoni Avatar answered Oct 22 '22 01:10

Pythoni