3 ms·
I'm not a particularly experienced programmer. It is a sign of my immature taste to find this ugly? The idea of assuming any exception thrown will be the except
by Tomminn 8y ago
I'm not a particularly experienced programmer. It is a sign of my immature taste to find this ugly? The idea of assuming any exception thrown will be the exception we expect (outside iteration limits) seems like an unnecessary abuse of the exception system. I'm really surprised it's the way such a fundamental construct in the language is written.
Is the idea here that all other exceptions will be thrown at the line "iter_object= iter(my_list)"? I guess this makes sense. But it still makes me uncomfortable. Should I become more comfortable with writing constructs like this?
- dijksterhuis 8y agoThat’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.
- Tomminn 8y agoDuh- 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?
- muthuraj57 8y agoI'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?
- uranusjr 8y agoSort 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.