By Lenin Mishra
This is the part of the 9th day in the Python 30 series. Check out the series here.
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, a
StopIterationException is raised.
y = [1, 2, 3] x = iter(y) print(x.__next__()) print(x.__next__()) print(x.__next__()) print(x.__next__())
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.
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")
1 2 3 StopIteration error handled successfully
Check out other Python Built-in Exception classes in Python.
- Try, Except, Else and Finally in Python
- ZeroDivisionError Exception in Python
- OverflowError Exception in Python
- ArithmeticError Exception in Python
- KeyError Exception in Python
- IndexError Exception in Python
- LookupError Exception in Python
- TypeError Exception in Python
- NameError Exception in Python
- FileNotFoundError Exception in Python
- Catch Multiple Exceptions in Python