Using "with" context handler, and catching specific exception?
Victor Hooi
victorhooi at gmail.com
Mon Oct 21 21:43:39 EDT 2013
Hi,
I suspect I'm holding
How should I use the "with" context handler as well as handling specific exceptions?
For example, for a file:
with open('somefile.log', 'wb') as f:
f.write("hello there")
How could I specifically catch IOError in the above, and handle that? Should I wrap the whole thing in a try-except block?
(For example, if I wanted to try a different location, or if I wanted to print a specific error message to the logfile).
try:
with open('somefile.log', 'wb' as f:
f.write("hello there")
except IOError as e:
logger.error("Uhoh, the file wasn't there").
Cheers,
Victor
More information about the Python-list
mailing list