ในบทช่วยสอนนี้ เราจะเรียนรู้ Try-Except สำหรับ Error และ Exception Handling ใน Python
ประเภทของข้อผิดพลาดใน Python
- Syntax Errors (ข้อผิดพลาดไวยากรณ์) - Python ไม่เข้าใจโค้ด ตรวจพบตอน compile time
- Exceptions (ข้อยกเว้น) - ข้อผิดพลาดที่เกิดขณะรันโปรแกรม (Runtime) เช่น
ZeroDivisionError,ValueError
เราไม่สามารถป้องกัน Syntax Errors ได้ แต่สามารถ จัดการ (handle) Exceptions ได้ด้วย try-except
Exception พบบ่อยใน Python
| Exception | สาเหตุ |
|---|---|
ZeroDivisionError | หารด้วยศูนย์ |
ValueError | ค่าที่ส่งให้ฟังก์ชันไม่เหมาะสม (เช่น int('abc')) |
IndexError | เข้าถึง index ที่ไม่มีอยู่ใน sequence |
KeyError | เข้าถึง key ที่ไม่มีใน dictionary |
ImportError | import โมดูลที่ไม่มีอยู่ |
IOError / OSError | เปิด/อ่าน/เขียนไฟล์ไม่ได้ |
KeyboardInterrupt | ผู้ใช้กด Ctrl+C |
ไวยากรณ์ Try-Except
try:
# โค้ดที่อาจเกิด exception
statement1
statement2
except ExceptionType:
# จัดการเมื่อเกิด exception ที่ระบุ
statement1
statement2
ลำดับการทำงาน
- รันโค้ดใน
tryblock - ถ้าไม่มี exception -> ข้าม
exceptไปเลย - ถ้ามี exception และตรงกับที่
exceptระบุ -> รันexceptblock - ถ้ามี exception แต่ ไม่ตรง กับ
except-> exception จะ propagate ขึ้นไป (crash ถ้าไม่มี handler อื่น) - สามารถมี
exceptหลายบล็อกสำหรับtryเดียวกันได้
ตัวอย่าง 1: ไม่มี Exception
try:
arr = [1, 2, 3, 4, 5]
two = arr[1] # index ถูกต้อง
print(f"We didn't get any errors {two}")
except IndexError:
print("The given index is not valid")
We didn't get any errors 2
ตัวอย่าง 2: เกิด IndexError
try:
arr = [1, 2, 3, 4, 5]
six = arr[6] # index ผิด -> IndexError
print(f"We didn't get any errors {six}")
except IndexError:
print("The given index is not valid")
The given index is not valid
ตัวอย่าง 3: Except ไม่ตรงกับ Exception ที่เกิด
try:
arr = [1, 2, 3, 4, 5]
six = arr[6] # เกิด IndexError
except ValueError: # จับ ValueError แทน -> ไม่จับได้
print("The given index is not valid")
IndexError: list index out of range
รูปแบบขยาย: Multiple Except, Else, Finally
try:
# risky code
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except (ValueError, TypeError) as e:
print(f"Invalid value: {e}")
else:
print("No exception occurred") # รันเมื่อไม่มี exception
finally:
print("Always executed") # รันตลอดเวลา (cleanup)
Best Practices
- จับ exception เฉพาะเจาะจง (avoid bare
except:) - ใช้
as eเพื่อเข้าถึง exception object - ใช้
finallyสำหรับ cleanup (ปิดไฟล์, ปิด connection) - อย่าใช้ try-except เพื่อควบคุม flow ปกติ (control flow)
สรุป
Try-Except เป็นกลไกสำคัญสำหรับเขียนโปรแกรมที่ทนทาน (robust) ให้จัดการ exception ได้อย่างเหมาะสมเพื่อไม่ให้โปรแกรม crash อย่างไม่คาดคิด
หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็นครับ