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

วิธีใช้ Try-Finally Clause Handle Exception ใน Python

finally clause รันเสมอ ไม่ว่าจะมี exception หรือไม่ (cleanup/termination)

กฎ: try ต้องมี either except หรือ finally (ไม่รวมกันได้ใน Python 2, Python 3 รวมได้)

ตัวอย่าง

try:
    foo = open('test.txt', 'w')
    foo.write("It's a test file to verify try-finally in exception handling!!")
    print('try block executed')
finally:
    foo.close()
    print('finally block executed')

ผลลัพธ์

try block executed
finally block executed

File ปิดได้แน่ใจ แม้มี exception