Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Catch StopIteration Exception ใน Python

Iterator หมดแล้ว next() จะ raise StopIteration (ไม่ใช่ error)

ตัวอย่าง

import sys

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

ผลลัพธ์


5
9
7

Python 3 ใช้ next(i) แทน i.next()