Using "with" context handler, and catching specific exception?
MRAB
python at mrabarnett.plus.com
Mon Oct 21 22:04:31 EDT 2013
On 22/10/2013 02:43, Victor Hooi wrote:
> 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?
>
Yes, it's as simple as that.
> (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").
>
More information about the Python-list
mailing list