title: Catch exception happening during Context Manager - Python
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/3642080/using-python-with-statement-with-try-except-block">Using python “with” statement with try-except block</a>  </p>
  </blockquote>
  
  
  
  <p>I'm using <code>open</code> to open a file in Python. I encapsulate the file handling in a <code>with</code> statement as such:</p>
  
  <pre><code>with open(path, 'r') as f:
      # do something with f
      # this part might throw an exception
  </code></pre>
  
  <p>This way I am sure my file is closed, even though an exception is thrown.</p>
  
  <p>However, I would like to handle the case where opening the file fails (an <code>OSError</code> is thrown).
  One way to do this would be put the whole <code>with</code> block in a <code>try:</code>. This works as long as the file handling code does not throw a OSError.</p>
  
  <p>It could look something like :</p>
  
  <pre><code>try:
     with open(path, 'rb') as f:
  except:
     #error handling
         # Do something with the file
  </code></pre>
  
  <p>This of course does not work and is really ugly. Is there a smart way of doing this ?</p>
  
  <p>Thanks</p>
  
  <p>PS: I'm using python 3.3</p>