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

วิธี Handle Exception ใน Python (พื้นฐาน)

วิธีง่ายที่สุด: try-except block

ตัวอย่าง

try:
    fob = open("test.txt", "r")
    fob.write("This is my test file for exception handling!!")
except IOError:
    print("Error: can't find the file or read data")
else:
    print("Write operation is performed successfully on the file")
    fob.close()

ผลลัพธ์

Error: can't find the file or read data

else รันเมื่อไม่มี exception