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

วิธี Ignore Exceptions ใน Python อย่างถูกต้อง

1. Bare except + pass (จับ BaseException รวม KeyboardInterrupt, SystemExit)

try:
    x, y = 7, 0
    z = x/y
except:
    pass

2. except Exception + pass (ไม่จับ KeyboardInterrupt, SystemExit)

try:
    x, y = 7, 0
    z = x/y
except Exception:
    pass

แนะนำ: ใช้ sys.exc_clear() ล้าง exception record

try:
    x, y = 7, 0
    z = x/y
except Exception:
    sys.exc_clear()

ป้องกัน object ใน exception statement อยู่ในหน่วยความจำจนกว่าจะมี exception ใหม่