Exception หมายถึง error ที่เกิดขึ้นกับ code ที่มี syntax ถูกต้อง
ยกตัวอย่างเช่น การหารเลขด้วย 0:
print(5 / 0)
ผลลัพธ์:
ZeroDivisionError
Exception สามารถทำให้ code หยุดทำงานหรือทำงานผิดพลาดได้
ดังนั้น ในการเขียน code เราควรกำหนดวิธีในการจัดการกับ exception เพื่อป้องกันไม่ให้ code ทำงานผิดพลาด
ใน Python เรามี 5 keywords สำหรับจัดการ exception ได้:
tryexceptelsefinallyraise
เราไปดูตัวอย่างการใช้งานทั้ง 5 keywords ผ่านตัวอย่าง code การจ่ายเงินออนไลน์กัน
- 🔨 try, except
- 🤔 else
- ☝️ finally
- 👋 raise
- 💪 สรุป 5 Keywords
- 📚 Further Reading: Python Exceptions
- 😺 GitHub
- 📃 References
🔨 try, except
try และ except เป็น keywords ที่ใช้ร่วมกัน โดยใน try เราจะใส่ code ที่เราคิดว่าอาจจะเกิด exception ขึ้นได้
ส่วนใน except เราจะใส่สิ่งที่เราต้องการให้เกิดขึ้นเมื่อเกิด exception ขึ้น
ยกตัวอย่างเช่น เราเขียน code เพื่อเช็กว่า payment มีค่ามากกว่า 0 หรือไม่ แต่ payment ที่ใส่เข้ามาอาจไม่ใช่ตัวเลข ซึ่งจะทำให้ code ของเราหยุดทำงาน:
# Without try, except
# Set payment
payment = "one thousand"
# Validate payment
if float(payment) < 0:
print("Payment cannot be negative.")
ผลลัพธ์:
ValueError
เราสามารถใช้ try และ except ช่วยให้ code ทำงานต่อได้ พร้อมทำให้บอกเราให้รู้ว่า เกิดข้อผิดพลาดอะไรขึ้น:
# Set payment
payment = "one thousand"
# Code that may raise exception
try:
if float(payment) < 0:
print("Payment cannot be negative.")
# Print when exception occurs
except ValueError:
print("Payment must be a number.")
ผลลัพธ์:
Payment must be a number.
🤔 else
else ทำงานคล้าย except แต่แทนที่จะส่งค่าบางอย่างกลับมาเมื่อเกิด exception, else จะทำงานเมื่อไม่มี exception เกิดขึ้นใน try
ยกตัวอย่างเช่น ใช้ else เพื่อแสดงข้อความว่ากำลังประมวลผล เมื่อ payment เป็นตัวเลข:
# Set payment
payment = 500
# Code that may raise exception
try:
if float(payment) < 0:
print("Payment cannot be negative.")
# Print when exception occurs
except ValueError as e:
print(f"Error: {e}")
# Print when exception does not occur
else:
print("Processing payment ...")
ผลลัพธ์:
Processing payment ...
☝️ finally
finally จะส่งค่ากลับมาไม่ว่าจะเกิด exception ขึ้นหรือไม่ก็ตาม
ยกตัวอย่างเช่น ใช้ finally แสดงข้อความขอบคุณลูกค้า ไม่ว่า payment จะผ่านหรือไม่ก็ตาม:
# Set payment
payment = 500
# Code that may raise exception
try:
if float(payment) < 0:
print("Payment cannot be negative.")
# Print when exception occurs
except ValueError as e:
print(f"Error: {e}")
# Print when exception does not occur
else:
print("Processing payment ...")
# Print no matter what
finally:
print("Thank you for your payment.")
ผลลัพธ์:
Processing payment ...
Thank you for your payment.
👋 raise
สุดท้าย เราจะใช้ raise กำหนด exception ได้เอง
ยกตัวอย่างเช่น ใช้ raise เพื่อแจ้งเตือนเมื่อ payment ติดลบ:
# Set payment
payment = -50
# Code that may raise exception
try:
if not isinstance(payment, (int, float)):
raise TypeError("Payment must be a number.")
if payment < 0:
raise ValueError("Payment cannot be negative.")
# Print when exception occurs
except (TypeError, ValueError) as e:
print(f"Error: {e}")
# Print when exception does not occur
else:
print("Processing payment ...")
# Print no matter what
finally:
print("Thank you for your payment.")
ผลลัพธ์:
Error: Payment cannot be negative.
Thank you for your payment.
💪 สรุป 5 Keywords
ในบทความนี้ เราได้เรียนรู้วิธีใช้ 5 keywords เพื่อจัดการ exception ใน Python ได้แก่:
try: รัน code ที่เราคิดว่าอาจเกิด exceptionexcept: code ที่จะรันเมื่อเกิด exception จาก tryelse: code ที่รันเมื่อไม่เกิด exception จาก tryfinally: code ที่จะรันไม่ว่าtryจะเกิด exception หรือไม่raise: code สำหรับแสดง exception ที่กำหนดเอง
ตัวอย่าง code:
# Set payments
payments = {
"Alex": "one thousand",
"Barbara": -50,
"Carter": 500
}
# Loop through payments
for name, payment in payments.items():
# Print name and payment
print(f"{name} paying {payment}.")
# Code that may raise exception
try:
if not isinstance(payment, (int, float)):
raise TypeError("Payment must be a number.")
if payment < 0:
raise ValueError("Payment cannot be negative.")
# Print when exception occurs
except (TypeError, ValueError) as e:
print(f"Error: {e}")
# Print when exception does not occur
else:
print("Processing payment ...")
# Print no matter what
finally:
print("Thank you for your payment.")
# Print divider
print("\\n -------------------------------------------------- \\n")
ผลลัพธ์:
Alex paying one thousand.
Error: Payment must be a number.
Thank you for your payment.
--------------------------------------------------
Barbara paying -50.
Error: Payment cannot be negative.
Thank you for your payment.
--------------------------------------------------
Carter paying 500.
Processing payment ...
Thank you for your payment.
--------------------------------------------------
📚 Further Reading: Python Exceptions
ศึกษาประเภทของ exception ใน Python ได้ที่: Python Built-in Exceptions
😺 GitHub
ดู code ทั้งหมดในบทความนี้ได้ที่ GitHub

Leave a comment