back

by dijksterhuis·7y ago·view on hn ↗
That’s not how it works.

“except StopIteration” only watches for the specific StopIteration exception coming from the next() call on the Iterator (the bit included in the try block).

If there was then an, for example, “except Error” line afterwards, then anything that causes an Error exception (ValueError, TypeError etc) would call those lines.

If you get any exception that has not been explicitly referenced in an except clause, then the program will halt, with that exception as the error output.

2 comments
Duh- reading comprehension fail- cheers. Same question though, there is still something that makes me uncomfortable about using exceptions as an expected-case control flow structure (as in, this is expected to catch an exception once every for loop call). Is that something I should get over, and should I write more code that uses exceptions in this fashion?
Python's official implementation is very slow and they don't care about performance. I wouldn't try to take any lessons from the way Python is implemented.
You are correct that this use of exceptions is very bad code smell.
I'm not familiar with Python since I'm from Java background. In Java throwing exceptions is costly (like null check is preferred over catching NPE) since exception needs to get stacktrace which involves quite a lot of reflection.

Is this the case with python too? or throwing exception is "free" here?

Sort of. In Python the stacktrace is always built for every step you take in code, so exceptions are not particularly costly compared to other operations. Reflection is also not relatively more costly since types are objects just like everything else.

It could even be more efficient than return value checking in certain cases.