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

วิธี Handle Python Exception ภายใน Loop

ห่อ loop ไว้ใน try-except

ตัวอย่าง

a = []
foo = 'redbullz'
try:
    for i in foo:
        a.append(i)
    print(a[8])  # IndexError
except Exception as e:
    print(e)

ผลลัพธ์

list index out of range
Process finished with exit code 0