Why exceptions shouldn't be used for flow control [Re: YAS to the "Reading line-by-line" Problem]
wtanksle at dolphin.openprojects.net
Wed Jun 30 01:15:57 CEST 1999
On Mon, 28 Jun 1999 11:17:01 +1200, Greg Ewing wrote:
>William Tanksley wrote:
>> while not f.eof():
>> line = f.readline()
>> # ...
>I'd love to be able to write reading loops that way.
>Unfortunately, it's a fact of life that some of the
>things read() has to deal with are unable to detect
>eof without trying to read something. I think the
>existing definition of read() and friends is the best
>that can be done in those circumstances.
I'd guess that you're talking about things like text file parsing and
such. I would use readline there, but that's fine. Yes, unstructured
data is more difficult to handle.
>> It's been a while since I've used read, so I
>> don't recall what it actually returns
>It returns an empty string if it can't read more
>than 0 characters, same as readline().
Ah. There's a justification for that, as you observed. I don't like the
fact that readline is stuck doing the same thing (record delimiters are
not really part of the record).
>> in a function designed to get n!=0
>> more characters, an EOF really is an error. Unfortunately for me, that's
>> not the definition of 'read', and never will be.
>Perhaps there should be a 2-parameter version of read:
> read(min, max)
>which would raise an exception if it couldn't read at
>least min characters. Setting min=0 would give the
>current behaviour, and setting min=max would allow
>reading a fixed-length record without having to check
>for errors. Then everyone would be happy!
A facinating solution. Well, since I don't use read, I probably wouldn't
use it, and I'm the only person whining. Therefore, it's probably not
worth implementing (even though it is a cool solution).
-William "Billy" Tanksley
More information about the Python-list