open() and EOFError

Chris Angelico rosuav at gmail.com
Mon Jul 7 04:09:28 EDT 2014


On Mon, Jul 7, 2014 at 6:00 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> How do people feel about code like this?
>
> try:
>     name = input("Enter file name, or Ctrl-D to exit")
>     # On Windows, use Ctrl-Z [enter] instead.
>     fp = open(name)
> except EOFError:
>     sys.exit()
> except IOError:
>     handle_bad_file(name)
> else:
>     handle_good_file(fp)

It seems trivial in this example to break it into two try blocks:

try:
    name = input("Enter file name, or Ctrl-D to exit")
    # On Windows, use Ctrl-Z [enter] instead.
except EOFError:
    sys.exit()
try:
    fp = open(name)
except IOError:
    handle_bad_file(name)
else:
    handle_good_file(fp)

But if the code's more complicated and it's not so easy to split, then
sure, doesn't seem a problem. It's like spam[foo//bar] and then
catching either IndexError or ZeroDivisionError - there's no big
confusion from having two distinct sources of two distinct errors
handled by two distinct except blocks.

ChrisA



More information about the Python-list mailing list