OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Catching an exception while using a Python 'with' statement

  • Thread starter Thread starter grigoryvp
  • Start date Start date
G

grigoryvp

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

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

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

and can't write

Code:
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?
<p>I can't figure out how to handle exception for python 'with' statement. If I have a code:</p>
<pre><code>with open("a.txt") as f:
print f.readlines()
</code></pre>
<p>I really want to handle 'file not found exception' in order to do something. But I can't write</p>
<pre><code>with open("a.txt") as f:
print f.readlines()
except:
print 'oops'
</code></pre>
<p>and can't write</p>
<pre><code>with open("a.txt") as f:
print f.readlines()
else:
print 'oops'
</code></pre>
<p>Enclosing <code>with</code> 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 <code>with</code> statement in a Pythonic way?</p>
 
Top