Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching an exception while using a Python 'with' statement

To my shame, 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 somehing. 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 else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?

like image 769
grigoryvp Avatar asked Apr 03 '09 13:04

grigoryvp


People also ask

How do you capture an exception in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

Which statement handles errors raised within the with statement?

Try and Except statement is used to handle these errors within our code in Python.

Which of the following error handling statement is used in Python?

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.

Can you throw an exception in an if statement?

should I use the throw outside or inside an "if" statement? You definitely should throw exception inside the if condition check.


1 Answers

from __future__ import with_statement  try:     with open( "a.txt" ) as f :         print f.readlines() except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available     print 'oops' 

If you want different handling for errors from the open call vs the working code you could do:

try:     f = open('foo.txt') except IOError:     print('error') else:     with f:         print f.readlines() 
like image 196
Douglas Leeder Avatar answered Oct 01 '22 18:10

Douglas Leeder