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

ข้อยกเว้นพื้นฐานใน Python


Python มีข้อยกเว้น (exceptions) มาตรฐานหลายประเภทที่มักเกิดขึ้นในโปรแกรม อาจถูกยกระaises โดยโปรแกรมเมอร์หรือโดยตัวอินเทอร์พรีเตอร์เอง ดังนี้:

AssertionError

เกิดเมื่อคำสั่ง assert ล้มเหลว ใช้สำหรับตรวจสอบเงื่อนไขที่ต้องเป็นจริงเสมอ

class MyClass:
    def __init__(self, x):
        self.x = x
        assert self.x > 50

myObj = MyClass(5)  # AssertionError

AttributeError

เกิดเมื่อพยายามเข้าถึง attribute ที่ไม่มีอยู่ในคลาส

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def getpoint(self):
        print('x= ' + str(self.x))
        print('y= ' + str(self.y))
        print('z= ' + str(self.z))  # AttributeError: no attribute 'z'

pt = Point(10, 20)
pt.getpoint()

ImportError

เกิดเมื่อคำสั่ง import ไม่สามารถนำเข้าโมดูลได้ หรือชื่อแพ็กเกจถูกต้องแต่ไม่พบโมดูล

from math import abcd  # ImportError: cannot import name 'abcd'

ModuleNotFoundError

ย่อยคลาสของ ImportError เกิดเมื่อไม่พบโมดูลที่ระบุ

import abcd  # ModuleNotFoundError: No module named 'abcd'

IndexError

เกิดเมื่อดัชนี (index) ของลำดับ (list, tuple, set) เกินขอบเขต

myList = [10, 20, 30, 40]
print(myList[5])  # IndexError: list index out of range

RecursionError

เกิดเมื่อการเรียกฟังก์ชันซ้ำ (recursion) เกินความลึกสูงสุด

def myFunction():
    myFunction()
myFunction()  # RecursionError: maximum recursion depth exceeded

StopIteration

เกิดเมื่อ iterator ไม่มีอิลิเมนต์เหลือ และเรียก next()

myList = [10, 20, 30, 40]
myIter = iter(myList)
while True:
    print(next(myIter))  # StopIteration หลังพิมพ์ 40

IndentationError

เกิดเมื่อรหัส Python มีการเยื้อง (indentation) ผิดพลาด สืบทอดมาจาก SyntaxError

for i in range(10):
print("The value of i: " + str(i))  # IndentationError: expected an indented block

TypeError

เกิดเมื่อดำเนินการกับออบเจ็กต์ชนิดไม่เหมาะสม เช่น ใช้ float เป็นดัชนี list

myList = [10, 20, 30, 40]
print(myList[1.25])  # TypeError: list indices must be integers or slices, not float

ZeroDivisionError

เกิดเมื่อหารด้วยศูนย์

print(5/0)  # ZeroDivisionError: division by zero