StopIteration Exception in Python

Handle StopIteration error in Python using the try-except block.

StopIteration Exception in Python
StopIteration Error in Python

To understand StopIteration Exception, you need to understand how iterators work in Python.

  1. Iterator is an object that holds values which can be iterated upon.
  2. It uses the __next__() method to move to the next value in the iterator.
  3. When the __next__() method tries to move to the next value, but there are no new values, a StopIteration Exception is raised.

Example 1

Code

y = [1, 2, 3]
x = iter(y)
print(x.__next__())
print(x.__next__())
print(x.__next__())
print(x.__next__())

Output

1
2
3
Traceback (most recent call last):
  File "some_file_location", line 6, in <module>
    print(x.__next__())
StopIteration

You can catch such errors using the StopIteration Exception class.


Example 2

Code

y = [1, 2, 3]
x = iter(y)
try:
    print(x.__next__())
    print(x.__next__())
    print(x.__next__())
    print(x.__next__())
except StopIteration as e:
    print("StopIteration error handled successfully")

Output

1
2
3
StopIteration error handled successfully

Check out other Python Built-in Exception classes in Python.

built-in-exception-classes - Pylenin
A programmer who aims to democratize education in the programming world and help his peers achieve the career of their dreams.

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe