Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Gợi ý cách clean hơn để handle Python exceptions?

Chúng ta có thể dùng mệnh đề finally để dọn dẹp سواء có exception được throw hay không:

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

Nếu cleanup cần được làm trong trường hợp có exception, chúng ta có thể code như sau:

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