คำว่าexceptในPython

ตัวอย่าง

ถ้าประโยคทำให้เกิดความผิดพลาด จะพิมพ์ "Something went wrong"

try:
  x > 3
except:
  print("Something went wrong")

ทดสอบตัวอย่าง

การกำหนดและการใช้งาน

ใช้คำว่าexceptในบล็อค try ... except มันกำหนดบล็อคความเข้ารหัสที่จะทำงานเมื่อบล็อค try ขึ้นความผิดพลาด

คุณสามารถกำหนดบล็อคต่าง ๆ สำหรับประเภทของความผิดพลาดต่าง ๆ และบล็อคที่จะทำงานเมื่อไม่มีปัญหา โปรดดูตัวอย่างด้านล่าง

ตัวอย่างเพิ่มเติม

ตัวอย่าง 1

ถ้ามีข้อผิดพลาด 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")

ทดสอบตัวอย่าง

ตัวอย่าง 2

พยายามปฏิบัติการบทความที่ส่งผลให้เกิดข้อผิดพลาด แต่ไม่ได้ระบุประเภทข้อผิดพลาด (ในกรณีนี้เป็น 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")

ทดสอบตัวอย่าง

ตัวอย่าง 3

ถ้าไม่มีข้อผิดพลาด เขียนข้อความหนึ่ง

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