讀書筆記--Python常見異常類

1.NameError
嘗試訪問一個未聲明的變量,會引發NameError。
例如:
print(foo)
錯誤信息如下:
Traceback (most recent call last): File “D:/PythonCode/Chapter09/異常.py”, line 1, in   print(foo)NameError: name ‘foo’ is not defined
上述信息表明,解釋器在任何命名空間裏面都沒有找到foo。
2.ZeroDivisionError
當除數爲零的時候,會引發ZeroDivisionError異常。
例如:1/0錯誤信息如下:
Traceback (most recent call last): File “D:/PythonCode/Chapter09/異常.py”, line 1, in   1/0ZeroDivisionError: division by zero
事實上,任何數值被零除都會導致上述異常。
3.SyntaxError
當解釋器發現語法錯誤時,會引發SyntaxError異常。
例如:
list = [“a”,“b”,“c”]
for i in list  
print(i)在上述示例中,由於for循環的後面缺少冒號,所以導致程序出現如下錯誤信息:
File “D:/PythonCode/Chapter09/異常.py”, line 2 for i in list  ^SyntaxError: invalid syntaxSyntaxError
異常是唯一不在運行時發生的異常,它代表着Python代碼中有一個不正確的結構,使得程序無法執行。這些錯誤一般是在編譯時發生,解釋器無法把腳本轉換爲字節代碼。
4.IndexError
當使用序列中不存在的索引時,會引發IndexError異常。
例如:
list = []list[0]
上述示例中,list列表中沒有任何元素,使用索引0訪問列表首位元素時,出現如下錯誤信息:
Traceback (most recent call last): File “D:/PythonCode/Chapter09/異常.py”, line 2, in   list[0]IndexError: list index out of range
上述信息表明,列表的索引值超出了列表的範圍。
5.KeyError
當使用映射中不存在的鍵時,會引發KeyError異常。
例如:
myDict = {‘host’:‘earth’,‘port’:80}myDict[‘server’]
上述示例中,myDict字典中只有host和port兩個鍵,獲取server鍵對應的值時,出現如下錯誤信息:
Traceback (most recent call last): File “D:/PythonCode/Chapter09/異常.py”, line 2, in   myDict[‘server’]KeyError: ‘server’
上述信息表明,出現了字典中沒有的鍵server。
6.FileNotFoundError
試圖打開不存在的文件時,會引發FileNotFoundError(Python 3.2以前是IOError)異常。
例如:
f = open(“test”)
上述示例中,使用open方法打開名爲test的文件或目錄,出現如下錯誤信息:
Traceback (most recent call last): File “D:/PythonCode/Chapter09/異常.py”, line 1, in   f = open(“test”)FileNotFoundError: [Errno 2] No such file or directory: ‘test’
上述信息表明,沒有找到名稱爲test的文件或者目錄。
7.AttributeError
當嘗試訪問未知的對象屬性時,會引發AttributeError異常。
例如:
class Car(object):  
passcar = Car()car.color = “黑色”
print(car.color)
print(car.name)
上述示例中,Car類沒有定義任何屬性和方法,在創建Car類的實例以後,動態地給car引用的實例添加了color屬性,然後訪問它的color和name屬性時,出現如下錯誤信息:
Traceback (most recent call last): File “D:/PythonCode/Chapter09/異常.py”, line 6, in   print(car.name)AttributeError: ‘Car’ object has no attribute ‘name’
上述信息表明,在Car的實例中定義了color屬性,所以可以使用car.color的方式訪問;但是沒有定義name屬性,所以訪問name屬性時就會出錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章