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

To understand StopIteration
Exception, you need to understand how iterators work in Python.
- Iterator is an object that holds values which can be iterated upon.
- It uses the
__next__()
method to move to the next value in the iterator. - When the
__next__()
method tries to move to the next value, but there are no new values, aStopIteration
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.
