Exceptions are not just for errors (was: My first Python program)
ben+python at benfinney.id.au
Wed Oct 13 22:20:27 CEST 2010
Seebs <usenet-nospam at seebs.net> writes:
> On 2010-10-13, Chris Rebert <clp2 at rebertia.com> wrote:
> > For future reference, the significant majority of things in Python
> > raise exceptions upon encountering errors rather than returning
> > error values of some sort.
> Yes. I'm getting used to that -- it's a bit of a shift, because I'm
> used to exceptions being *exceptional* -- as in, not a failure mode
> you would expect to see happening.
>From that expectation, it's an even more fundamental shift. Python
encourages (and tends toward) raising exceptions in any exceptional
circumstance — that is, in any circumstance that isn't the usual
behaviour for the function.
So, for example, an exception (StopIteration) is how iterables signal
that they've finished iterating; but that's not an error, only an
exception. Likewise for the ‘str.index’ example given earlier.
> So for instance, I wouldn't expect to get an exception for EOF,
> because that's not exceptional, that's virtually guaranteed to happen
> whenever you interact with files. I am gonna have to retrain a bit.
EOF is exceptional in that it's not the normal behaviour for “read some
bytes from a file and return them”. EOF is expected – hence it has a
code path for handling that circumstance – but it's not normal.
Another way of thinking about it is that there's no sensible sequence of
bytes to return at EOF, so the Pythonic thing to do is to raise an
exception for this exceptional circumstance.
So your expectations on this point, while not unusual, do need
retraining as you say :-)
\ “In the long run nothing can withstand reason and experience, |
`\ and the contradiction which religion offers to both is all too |
_o__) palpable.” —Sigmund Freud |
More information about the Python-list