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

วิธี Catch Python Exception ใน List Comprehension

List comprehension มีแค่ expressions ไม่มี statements → ไม่สามารถ catch exception ได้โดยตรง

Workaround: Delegate ไปยัง helper function

ตัวอย่าง

foo = (5, 7, 1, 0, 9)

def bar(self):
    try:
        return [1/i for i in foo]
    except ZeroDivisionError as e:
        print(e)

bar(foo)

ผลลัพธ์

integer division or modulo by zero
Process finished with exit code 0

หรือตรวจสอบค่าก่อน (guard clauses) แทนการ catch