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


Groups > comp.lang.python > #74148

error handling when opening files

Date 2014-07-08 01:49 +0200
Subject error handling when opening files
From Alex Burke <alexjeffburke@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.11616.1404796682.18130.python-list@python.org> (permalink)

Show all headers | View raw


Hi there,

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?

The reason I preferred the second was in addition to catching the
IOError when attempting the open() if the file does not exist I
thought I was accounting for the possibility en error occurs while
reading data out of the file. That and to handle if do_stuff() was
actually calling readline() or such on the file which I thought was
possible source of issues.

I am wondering if this is also related to some misunderstanding around
the file context manager - on exit of the with() block a close is
arranged, but if that close() is called in an error situation I was
under the impression that the error would be raised again outside it.
Otherwise the only way I can see of getting errors is have a variable
set to None and if the with block succeeds set it to some other value
thus being able to do an if not None check afterward.

That's probably enough conflated questioning for now.. who'd have
thought opening a file could be such a poser! Yep, it's always the
error handling :)

Thanks in advance, Alex J Burke.

Back to comp.lang.python | Previous | NextNext 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