常見(jiàn)異常
異常 | 描述 |
---|---|
NameError | 嘗試訪(fǎng)問(wèn)一個(gè)沒(méi)有申明的變量 |
ZeroDivisionError | 除數(shù)為0 |
SyntaxError | 語(yǔ)法錯(cuò)誤 |
IndexError | 索引超出序列范圍 |
KeyError | 請(qǐng)求一個(gè)不存在的字典關(guān)鍵字 |
IOError | 輸入輸出錯(cuò)誤(例如要讀取的文件不存在 ) |
AttributeError | 嘗試訪(fǎng)問(wèn)位置的對(duì)象屬性 |
簡(jiǎn)單介紹下
NameError
wxx
變量沒(méi)有初始化,即沒(méi)有賦值腮介。因?yàn)樽兞肯喈?dāng)于一個(gè)標(biāo)簽肥矢,要將其貼到對(duì)象上才有意義。
>>> wxx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'wxx' is not defined
ZeroDivisionError
除數(shù)為0
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
SyntaxError
語(yǔ)法錯(cuò)誤叠洗,編譯時(shí)無(wú)法正確轉(zhuǎn)化為Python字節(jié)碼甘改,故報(bào)錯(cuò)旅东,只有修改正確之后才能編譯成功。
>>> def func()
File "<stdin>", line 1
def func()
^
SyntaxError: invalid syntax
IndexError
索引超過(guò)范圍十艾。這個(gè)道理告訴我們充大頭鬼需要付出代價(jià)抵代。
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> f = range(10)
>>> f[11]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
KeyError
如果字典中不存在該關(guān)鍵字,報(bào)錯(cuò)疟羹。純屬無(wú)中生有了主守。
>>> dic = {'name':'wxx','age':'23'}
>>> dic['height']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'height'
IOError
文件不存在。怎么可能有這個(gè)文件榄融。
>>> file = open("nvyou.avi")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'nvyou.avi'
AttributeError
屬性不存在参淫,純屬無(wú)中生有。
>>> def func():
... a = 1
...
>>> fu = func()
>>> fu.b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'b'