Search code examples
pythonexception

Catching an exception while using a Python 'with' statement


I can't figure out how to handle exception for python 'with' statement. If I have a code:

with open("a.txt") as f:
    print f.readlines()

I really want to handle 'file not found exception' in order to do something. But I can't write

with open("a.txt") as f:
    print f.readlines()
except:
    print 'oops'

and can't write

with open("a.txt") as f:
    print f.readlines()
else:
    print 'oops'

Enclosing with in a try/except statement doesn't work either, and an exception is not raised. What can I do in order to process failure inside with statement in a Pythonic way?


Solution

  • This solution will keep the with-block-code outside of the try-except-clause.

    try:
        f = open('foo.txt')
    except FileNotFoundError:
        print('error')
    else:
        with f:
            print f.readlines()