Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #74151

Re: error handling when opening files

From Marko Rauhamaa <marko@pacujo.net>
Newsgroups comp.lang.python
Subject Re: error handling when opening files
Date 2014-07-08 11:30 +0300
Organization A noiseless patient Spider
Message-ID <87fvicgslh.fsf@elektro.pacujo.net> (permalink)
References <mailman.11616.1404796682.18130.python-list@python.org>

Show all headers | View raw


Alex Burke <alexjeffburke@gmail.com>:

> While reading up on a previous thread 'open() and EOFError' I saw the
> following (with minor changes to help make my question clearer) block
> suggested as a canonical way to open files and do something:
>
> try:
>     f = open(path)
> except IOError:
>     handle_error()
> else:
>     with f:
>         do_stuff()
>
> This somewhat surprised me because I'd always written such a block
> something more as follows:
>
> try:
>     with open(path) as f:
>         do_stuff()
> except IOError:
>     handle_error('file never opened')
> except ApplicationError:
>     handle_error('doing something with the content went wrong')
>
> Aside from the pythonic but less widely known else clause of the
> try/except in the first form, what else is different? What nuances am
> I missing?

Your version catches IOError for do_stuff() as well as open(). You
usually want to guard each statement with try-except so you can log and
pinpoint the error better.


Marko

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

error handling when opening files Alex Burke <alexjeffburke@gmail.com> - 2014-07-08 01:49 +0200
  Re: error handling when opening files Marko Rauhamaa <marko@pacujo.net> - 2014-07-08 11:30 +0300
  Re: error handling when opening files Steven D'Aprano <steve@pearwood.info> - 2014-07-08 09:00 +0000
    Re: error handling when opening files Chris Angelico <rosuav@gmail.com> - 2014-07-08 20:35 +1000
    Re: error handling when opening files Alex Burke <alexjeffburke@gmail.com> - 2014-07-09 21:59 +0200
  Re: error handling when opening files wxjmfauth@gmail.com - 2014-07-08 02:38 -0700

csiph-web