Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch StopIteration Exception in Python?

In the following code, I am getting an error

   z = [5, 9, 7]
   i = iter(z)
   print i
   print i.next()
   print i.next()
   print i.next()
   print i.next()

How do I catch this error and know its type?


1 Answer
Rajendra Dharmkar

When an iterator is done, it’s next method raises StopIteration. This exception is not considered an error.

We re-write the given code as follows to catch the exception and know its type.

import sys
try:
z = [5, 9, 7]
i = iter(z)
print i
print i.next()
print i.next()
print i.next()
print i.next()
except Exception as e:
print e
print sys.exc_type

OUTPUT

<listiterator object at 0x0000000002AF23C8>
5
9
7
<type 'exceptions.StopIteration'>
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.