Using "with" context handler, and catching specific exception?

Victor Hooi victorhooi at gmail.com
Mon Oct 21 23:27:05 EDT 2013


Hi,

Thanks for the replies =).

Aha, good point about IOError encapsulating other things, I'll use FileNotFoundError, and also add in some other except blocks for the other ones.

And yes, I didn't use the exception object in my sample - I just sort. I'd probably be doing something like this.

    logger.error("Some error message - %s" % e) 

So is the consensus then that I should wrap the "with" in a try-except block?

    try: 
          with open('somefile.log', 'wb') as f: 
              f.write("hello there") 
    except FileNotFoundError as e: 
        logger.error("Uhoh, the file wasn't there - %s" % e) 

Cheers,
Victor

On Tuesday, 22 October 2013 14:04:14 UTC+11, Ben Finney  wrote:
> Victor Hooi <victorhooi at gmail.com> writes:
> 
> 
> 
> >     try:
> 
> >         with open('somefile.log', 'wb' as f:
> 
> >             f.write("hello there")
> 
> >     except IOError as e:
> 
> >         logger.error("Uhoh, the file wasn't there").
> 
> 
> 
> IOError, as Steven D'Aprano points out, is not equivalent to “file not
> 
> found”. Also, you're not doing anything with the exception object, so
> 
> there's no point binding it to the name ‘e’.
> 
> 
> 
> What you want is the specific FileNotFoundError:
> 
> 
> 
>     try:
> 
>         with open('somefile.log', 'wb' as f:
> 
>             f.write("hello there")
> 
>     except FileNotFoundError:
> 
>         logger.error("Uhoh, the file wasn't there").
> 
> 
> 
> See <URL:http://docs.python.org/3/library/exceptions.html#FileNotFoundError>.
> 
> 
> 
> -- 
> 
>  \            “Choose mnemonic identifiers. If you can't remember what |
> 
>   `\                mnemonic means, you've got a problem.” —Larry Wall |
> 
> _o__)                                                                  |
> 
> Ben Finney



More information about the Python-list mailing list