Keep your try
/ except
statement as close to the source of the exception as possible.
If you are not catching IOError
s, put it inside the with
statement. On the other hand, if it is an exception that open()
throws, put it around the with
statement.
If the with
statement is longer or you don't want to mask the same exception being raised in the with
statement suite, execute the open()
call first:
try:
fileobj = open(filename)
except IOError:
print('File problems!')
else:
with fileobj as f:
# do something