0

I learnt in the past that Exception should be fired when there is somthing in the program which is not normal. For example an error when reading a file. If you look this python code you will see that a StopIteration Exception is fired. But this is not an anormal behaviour of the program. So my question is: Should we raise an exception in this case ? Thanks

class MyIterator():
    def __init__(self, n):
        self.max = n

    def __iter__(self):
        self.count = 0
        return self

    # For Python3
    def __next__(self):
        if self.count == self.max:
            raise StopIteration
        self.count += 1
        return self.count - 1

c = MyIterator(4)
for i in c:
   print(i)
3
  • 2
    Yes you should. It tells the for loop the iterator reached the end. Commented Aug 30, 2017 at 20:55
  • 3
    Specifically: yes, that's how the iterator protocol works, as documented. Generally: it's common in Python to use exceptions for flow control - it's easier to ask for forgiveness than permission. Commented Aug 30, 2017 at 20:55
  • Relevant documentation is here by the way. Commented Aug 30, 2017 at 20:56

2 Answers 2

3

Yes. You not only should raise an exception here, you must raise an exception here. This is what the iterator protocol calls for:

iterator.__next__()

Return the next item from the container. If there are no further items, raise the StopIteration exception. [...]

You're correct in that exceptions should be raised when the program is in an exceptional state (yes, I know that sounds redundant). However, exceptions in Python are different than in most languages. Exceptions in Python are used for core language features such as iteration, and they are preferred over conditional statements. The common idiom in Python is that "It's easier to ask for foreignness instead of permission":

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

The try statement is also fined-tuned to allow for the user to have control over how exceptions are handled. It allows else, finally, and multiple except clasues to be used in conjugation with it.

Sign up to request clarification or add additional context in comments.

2 Comments

@Blckknght Thanks, I accidentally posted the link instead of the content at the link.
That's what I figured. I was initially just going to edit to fix the "your"->"you're" typo, but looked for other stuff to change at the same time and thought that looked like a copy and paste error.
1

Yes, absolutely. The StopIteration exception needs to be raised to signal iterator when the self.count equals to self.max which means there are no more elements. Look at Python's Iterator documentation

If there are no more elements in the stream, next() must raise the StopIteration exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.