Python 中的具體異常
Python 中有一些常見的異常。這些異常通常在不同的程式中引發。它們可能是由程式設計師顯式引發,也可能是 Python 直譯器隱式引發。其中一些異常包括:
異常 AssertionError
當斷言語句失敗時,可能會引發 AssertionError。在 Python 中,我們也可以在程式碼中設定一些斷言語句。斷言語句必須始終為真。如果條件失敗,它將引發 AssertionError。
示例程式碼
class MyClass: def __init__(self, x): self.x = x assert self.x > 50 myObj = MyClass(5)
輸出
--------------------------------------------------------------------------- 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:
異常 AttributeError
當我們嘗試訪問類的某個屬性,但該屬性不存在時,可能會引發 AttributeError。
示例程式碼
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()
輸出
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'
異常 ImportError
當**import**語句遇到匯入某個模組的問題時,可能會發生 ImportError。當 from 語句的包名稱正確,但找不到指定名稱的模組時,也可能會引發此異常。
示例程式碼
from math import abcd def __init__(self, x=0, y=0):
輸出
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-23-ff4519a07c77> in <module>() ----> 1 from math import abcd ImportError: cannot import name 'abcd'
異常 ModuleNotFoundError
它是 ImportError 的子類。當找不到模組時,可能會引發此錯誤。當 sys.modules 中找不到**None**時,也可能會引發此錯誤。
示例程式碼
import abcd
輸出
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-24-7b45aaa048eb> in <module>() ----> 1 import abcd ModuleNotFoundError: No module named 'abcd'
異常 IndexError
當序列(列表、元組、集合等)的下標超出範圍時,可能會引發 IndexError。
示例程式碼
myList = [10, 20, 30, 40] print(str(myList[5]))
輸出
--------------------------------------------------------------------------- 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
異常 RecursionError
RecursionError 是一個執行時錯誤。當超過最大遞迴深度時,它將被引發。
示例程式碼
def myFunction(): myFunction() myFunction()
輸出
--------------------------------------------------------------------------- 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
異常 StopIteration
在 Python 中,我們可以透過名為 next() 的內建方法獲得 StopIteration 錯誤。當迭代器沒有更多元素時,next() 方法將引發 StopIteration 錯誤。
示例程式碼
myList = [10, 20, 30, 40] myIter = iter(myList) while True: print(next(myIter))
輸出
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:
異常 IndentationError
當 Python 程式碼中存在無效縮排時,它將引發此類錯誤。它繼承了 Python 的**SyntaxError**類。
示例程式碼
for i in range(10): print("The value of i: " + str(i))
輸出
File "<ipython-input-44-d436d50bbdc8>", line 2 print("The value of i: " + str(i)) ^ IndentationError: expected an indented block
異常 TypeError
當對不適當型別的物件執行操作時,可能會發生 TypeError。例如,如果我們在陣列索引中提供浮點數,它將返回 TypeError。
示例程式碼
muList = [10, 20, 30, 40] print(myList[1.25])
輸出
--------------------------------------------------------------------------- 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
異常 ZeroDivisionError
當除法運算的分母為 0(零)時,將引發 ZeroDivisionError。
示例程式碼
print(5/0)
輸出
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-48-fad870a50e27> in <module>() ----> 1 print(5/0) ZeroDivisionError: division by zero
廣告