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

วิธีที่ดีที่สุดจัดการ List Empty Exception ใน Python

List เป็น Ordered Sequence เข้าถึง Element ด้วย Index 0 ถึง Length-1 หาก Index เกิน Range จะได้ IndexError Exception

ตัวอย่าง: ใช้ Infinite Loop Pop Element ทีละตัว Loop พยายามไปหลัง Pop จนหมด จะได้ IndexError จับด้วย Try-Except

a=[1,2,3]
while True:
    try:
        b=a.pop()
        print(b)
    except IndexError:
        break

แนะนำ: ใช้ if a: เช็คว่ามี Element ก่อน Pop หรือใช้ for item in a: วนโดยตรง ไม่ต้องจัดการ Exception