Python ยกเว้นคำหลัก
ตัวอย่าง
หากคำสั่งทำให้เกิดข้อผิดพลาดให้พิมพ์ "มีบางอย่างผิดพลาด":
try:
x > 3
except:
print("Something went wrong")
ความหมายและการใช้งาน
except
คีย์เวิร์ดใช้ในการ ลอง...ยกเว้นบล็อก มันกำหนดกลุ่มของรหัสที่จะเรียกใช้หากบล็อกการลองทำให้เกิดข้อผิดพลาด
คุณสามารถกำหนดบล็อคต่างๆ สำหรับข้อผิดพลาดประเภทต่างๆ และบล็อกที่จะดำเนินการถ้าไม่มีอะไรผิดพลาด ดูตัวอย่างด้านล่าง
ตัวอย่างเพิ่มเติม
ตัวอย่าง
เขียนข้อความหนึ่งว่าเป็น NameError และอีกข้อความหนึ่งเป็น TypeError:
x = "hello"
try:
x > 3
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
ตัวอย่าง
พยายามเรียกใช้คำสั่งที่ก่อให้เกิดข้อผิดพลาด แต่ไม่มีประเภทข้อผิดพลาดที่กำหนดไว้ (ในกรณีนี้คือ ZeroDivisionError):
try:
x = 1/0
except NameError:
print("You have a
variable that is not defined.")
except TypeError:
print("You
are comparing values of different type")
except:
print("Something else went wrong")
ตัวอย่าง
เขียนข้อความหากไม่มีข้อผิดพลาดเกิดขึ้น:
x = 1
try:
x > 10
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
else:
print("The 'Try' code was executed without raising any errors!")
หน้าที่เกี่ยวข้อง
try
คีย์เวิร์ด.
finally
คีย์เวิร์ด.