Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #74151
| Path | csiph.com!usenet.pasdenom.info!gegeweb.org!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail |
|---|---|
| From | Marko Rauhamaa <marko@pacujo.net> |
| Newsgroups | comp.lang.python |
| Subject | Re: error handling when opening files |
| Date | Tue, 08 Jul 2014 11:30:50 +0300 |
| Organization | A noiseless patient Spider |
| Lines | 35 |
| Message-ID | <87fvicgslh.fsf@elektro.pacujo.net> (permalink) |
| References | <mailman.11616.1404796682.18130.python-list@python.org> |
| Mime-Version | 1.0 |
| Content-Type | text/plain; charset=us-ascii |
| Injection-Info | mx05.eternal-september.org; posting-host="ff5cf27ef3d5b31f034d3b72bdc27a41"; logging-data="13614"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/LQknj79Q5LXy0bPPCfd8k" |
| User-Agent | Gnus/5.13 (Gnus v5.13) Emacs/23.3 (gnu/linux) |
| Cancel-Lock | sha1:FfQ7Lb7aFJgd6hNv8kPjCYQzq8Q= sha1:JzOJbnQe/FfXjuJV6YpD3SY92s0= |
| Xref | csiph.com comp.lang.python:74151 |
Show key headers only | 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 | Next — Previous in thread | Next in thread | Find similar | Unroll 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