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

วิธี Handle Python Exceptions ให้สะอาด (Cleaner)

1. ใช้ finally สำหรับ cleanup เสมอ

try:
    # some code
except:
    handle_exception()
finally:
    do_cleanup()

2. Cleanup เฉพาะตอนมี exception

should_cleanup = True
try:
    # some code
    should_cleanup = False
except:
    handle_exception()
finally:
    if should_cleanup:
        do_cleanup()