Why exceptions shouldn't be used for flow control [Re: YAS to the "Reading line-by-line" Problem]

Greg Ewing greg.ewing at compaq.com
Wed Jun 23 19:55:35 EDT 1999

William Tanksley wrote:
> Both should be handled by exception, not by returning a special
> value.

I don't agree with that. Reaching the end of a file while
reading it is not exceptional enough to warrant requiring
the use of an exception handler to catch it.

What bothers me about using exceptions for flow control
in situations like this is that the effect of an exception
handler is *non-local*, whereas what you're trying to
catch is really only a local concern.

When you write something like

  while 1:
      line = read_me_a_line()
    except EOFError:

what you really mean by the try-except is "if THIS
PARTICULAR reading operation reaches the end of
the file". But that's not what it does - it catches
any EOFError raised by any operation invoked by
read_me_a_line() that wasn't caught by something
else first.

In my experience, that sort of behaviour tends to
mask bugs. I prefer results which are not errors to
be returned normally, so that I can be sure where
they came from.


More information about the Python-list mailing list