Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách catch StopIteration Exception trong Python?

Khi iterator xong, method next của nó raise StopIteration. Exception này không được coi là error.

Chúng ta viết lại code cho trước như sau để catch exception và biết type của nó.

Ví dụ

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)

Kết quả

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