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

Try-Except ใน Python: การจัดการข้อผิดพลาดและข้อยกเว้น

ในบทช่วยสอนนี้ เราจะเรียนรู้ Try-Except สำหรับ Error และ Exception Handling ใน Python

ประเภทของข้อผิดพลาดใน Python

  1. Syntax Errors (ข้อผิดพลาดไวยากรณ์) - Python ไม่เข้าใจโค้ด ตรวจพบตอน compile time
  2. Exceptions (ข้อยกเว้น) - ข้อผิดพลาดที่เกิดขณะรันโปรแกรม (Runtime) เช่น ZeroDivisionError, ValueError

เราไม่สามารถป้องกัน Syntax Errors ได้ แต่สามารถ จัดการ (handle) Exceptions ได้ด้วย try-except

Exception พบบ่อยใน Python

Exceptionสาเหตุ
ZeroDivisionErrorหารด้วยศูนย์
ValueErrorค่าที่ส่งให้ฟังก์ชันไม่เหมาะสม (เช่น int('abc'))
IndexErrorเข้าถึง index ที่ไม่มีอยู่ใน sequence
KeyErrorเข้าถึง key ที่ไม่มีใน dictionary
ImportErrorimport โมดูลที่ไม่มีอยู่
IOError / OSErrorเปิด/อ่าน/เขียนไฟล์ไม่ได้
KeyboardInterruptผู้ใช้กด Ctrl+C

ไวยากรณ์ Try-Except

try:
    # โค้ดที่อาจเกิด exception
    statement1
    statement2
except ExceptionType:
    # จัดการเมื่อเกิด exception ที่ระบุ
    statement1
    statement2

ลำดับการทำงาน

  1. รันโค้ดใน try block
  2. ถ้าไม่มี exception -> ข้าม except ไปเลย
  3. ถ้ามี exception และตรงกับที่ except ระบุ -> รัน except block
  4. ถ้ามี exception แต่ ไม่ตรง กับ except -> exception จะ propagate ขึ้นไป (crash ถ้าไม่มี handler อื่น)
  5. สามารถมี 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 อย่างไม่คาดคิด


หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็นครับ