Có một số ngoại lệ phổ biến trong Python. Các ngoại lệ này thường được ném ra trong nhiều chương trình khác nhau. Chúng có thể được ném bởi lập trình viên một cách tường minh, hoặc trình thông dịch Python có thể ném chúng ngầm định. Một số ngoại lệ như sau:
Ngoại lệ AssertionError
AssertionError được ném khi một câu lệnh assert thất bại. Trong Python, ta có thể đặt các câu lệnh assert trong mã. Câu lệnh assert luôn phải đúng; nếu điều kiện thất bại, nó sẽ ném AssertionError.
Ví dụ mã
class MyClass:
def __init__(self, x):
self.x = x
assert self.x > 50
myObj = MyClass(5)
Kết quả
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-21-71785acdf821> in <module>()
4 assert self.x > 50
5
----> 6 myObj = MyClass(5)
<ipython-input-21-71785acdf821> in __init__(self, x)
2 def __init__(self, x):
3 self.x = x
----> 4 assert self.x > 50
5
6 myObj = MyClass(5)
AssertionError:
Ngoại lệ AttributeError
AttributeError được ném khi ta cố truy cập thuộc tính của một lớp mà thuộc tính đó không tồn tại.
Ví dụ mã
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))
pt = point(10, 20)
pt.getpoint()
Kết quả
x= 10
y= 20
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-15-f64eb52b2192> in <module>()
10
11 pt = point(10, 20)
----> 12 pt.getpoint()
<ipython-input-15-f64eb52b2192> in getpoint(self)
7 print('x= ' + str(self.x))
8 print('y= ' + str(self.y))
----> 9 print('z= ' + str(self.z))
10
11 pt = point(10, 20)
AttributeError: 'point' object has no attribute 'z'
Ngoại lệ ImportError
ImportError xảy ra khi câu lệnh import gặp sự cố khi nhập một module. Nó cũng có thể được ném khi tên gói trong câu lệnh from đúng nhưng không tìm thấy module với tên chỉ định.
Ví dụ mã
from math import abcd
Kết quả
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-23-ff4519a07c77> in <module>() ----> 1 from math import abcd ImportError: cannot import name 'abcd'
Ngoại lệ ModuleNotFoundError
Đây là lớp con của ImportError. Khi một module không được tìm thấy, lỗi này được ném. Nó cũng có thể được ném khi tìm thấy None trong sys.modules.
Ví dụ mã
import abcd
Kết quả
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-24-7b45aaa048eb> in <module>() ----> 1 import abcd ModuleNotFoundError: No module named 'abcd'
Ngoại lệ IndexError
IndexError được ném khi chỉ số của một sequence (List, Tuple, Set, v.v.) vượt quá phạm vi.
Ví dụ mã
myList = [10, 20, 30, 40] print(str(myList[5]))
Kết quả
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-29-a86bd85b04c9> in <module>()
1 myList = [10, 20, 30, 40
----> 2 print(str(myList[5]))
IndexError: list index out of range
Ngoại lệ RecursionError
RecursionError là lỗi runtime. Khi độ sâu đệ quy tối đa bị vượt quá, lỗi này được ném.
Ví dụ mã
def myFunction():
myFunction()
myFunction()
Kết quả
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-39-8a59e0fb982f> in <module>()
2 myFunction()
3
----> 4 myFunction()
<ipython-input-39-8a59e0fb982f> in myFunction()
1 def myFunction():
----> 2 myFunction()
3
4 myFunction()
... last 1 frames repeated, from the frame below ...
<ipython-input-39-8a59e0fb982f> in myFunction()
1 def myFunction():
----> 2 myFunction()
3
4 myFunction()
RecursionError: maximum recursion depth exceeded
Ngoại lệ StopIteration
Trong Python, ta có thể gặp StopIteration bằng phương thức built-in next(). Khi một iterator không còn phần tử nào, next() sẽ ném StopIteration.
Ví dụ mã
myList = [10, 20, 30, 40]
myIter = iter(myList)
while True:
print(next(myIter))
Kết quả
10
20
30
40
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-42-e608e2162645> in <module>()
2 myIter = iter(myList)
3 while True:
----> 4 print(next(myIter))
StopIteration:
Ngoại lệ IndentationError
Khi có thụt lề không hợp lệ trong mã Python, lỗi này được ném. Nó kế thừa từ lớp SyntaxError.
Ví dụ mã
for i in range(10):
print("The value of i: " + str(i))
Kết quả
File "<ipython-input-44-d436d50bbdc8>", line 2
print("The value of i: " + str(i))
^
IndentationError: expected an indented block
Ngoại lệ TypeError
TypeError xảy ra khi một phép toán được thực hiện trên đối tượng kiểu không phù hợp. Ví dụ, nếu cung cấp số thực làm chỉ số mảng, sẽ trả về TypeError.
Ví dụ mã
muList = [10, 20, 30, 40] print(myList[1.25])
Kết quả
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-46-e0a2a05cd4d4> in <module>()
1 muList = [10, 20, 30, 40
----> 2 print(myList[1.25])
TypeError: list indices must be integers or slices, not float
Ngoại lệ ZeroDivisionError
Khi mẫu số bằng 0 trong phép chia, ZeroDivisionError được ném.
Ví dụ mã
print(5/0)
Kết quả
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-48-fad870a50e27> in <module>() ----> 1 print(5/0) ZeroDivisionError: division by zero