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

วิธี Catch SystemExit Exception ใน Python

SystemExit ไม่ใช่ subclass ของ Exception แต่เป็น subclass ของ BaseException

วิธีที่ 1: Catch BaseException

try:
    raise SystemExit
except BaseException:
    print("It works!")

วิธีที่ 2: Catch SystemExit โดยตรง (แนะนำ)

try:
    raise SystemExit
except SystemExit:
    print("It works!")

ผลลัพธ์

It works!

Design: ไม่ให้ถูก catch โดย except Exception ตรงๆ