Hacker News new | ask | show | jobs
by protomyth 4672 days ago
Going one step further on the file example, I had a college professor who wrote a function read from a file that had no end except an exception thrown by the read because the file was at its end[1]. He said the end-of-file was an exceptional circumstance for a function that expected to read and process a line.

I doubt anyone would say end-of-file is unexpected, but I am not sure I would say it was exceptional.

1) something like this (it has been 20yrs)

  init data structure S
  open file A
  loop
    read line from A
    process line and add to S
  next
  catch EOF
    close A
    return S
  catch file-not-found
    return empty S
any mistakes are my memory not my old professor
1 comments

In Java, everyone would tell you this is wrong. In Python, this is the normal way to end an iteration (specifically, throwing StopIteration). It's not a huge leap to see a stream as an iteration over bytes. So, what's considered exceptional seems somewhat culturally dependent.
Note that in Python you usually use the syntactic sugar of for loops rather than interacting with StopIteration manually.
True! I should have made that clearer.

The only time you need to think about StopIteration is if you're consuming from an iterator in some unusual way (eg writing a "get me the single item which is in this iterator, or blow up if there are zero or more than one" function) or if you're writing an iterator which is not built out of building blocks which already know how to stop an iteration.

So, not often.