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

อธิบาย Try Except Finally Statements ใน Python

try-except: จับและจัดการ exceptions

ตัวอย่าง

try:
    'apple' + 6
except Exception:
    print("Cannot concatenate 'str' and 'int' objects")

ผลลัพธ์

Cannot concatenate 'str' and 'int' objects

หลีกเลี่ยง traceback ด้วยข้อความง่ายๆ

finally: optional clause รันเสมอ ก่อนออกจาก try statement (cleanup actions)

ตัวอย่าง File operations

try:
    f = open("foo.txt", encoding='utf-8')
    # perform file operations
finally:
    f.close()

รับประกันไฟล์ปิดได้ ทั้งมี exception และไม่มี