標籤:錯誤 異常 python 異常處理 異常捕獲
0.說明
如果想寫出使用者體驗高的代碼,那麼就需要考慮到在執行自己寫的這段代碼中在和使用者互動的過程中可能會出現的問題,也就是說,需要對可能出現的異常進行處理,只有做好這些工作,才能寫出使用者體驗好的代碼。
1.什麼是異常
錯誤是文法(導致解譯器無法解釋)或邏輯(也就是代碼品質問題)上的,在Python中,當檢測到錯誤時,解譯器會指出當前流無法繼續執行下去,於是就出現了異常。
程式出現了錯誤而在正常控制流程以外採取的行為。
根據上面的解釋,可以理解為,只要解譯器檢測到程式運行時出現了錯誤(與Python解譯器不相容而導致),就會觸發一個異常。
2.Python中的異常
如下:
異常類型 |
描述 |
簡單例子 |
NameError |
嘗試訪問一個未聲明的變數,或者是在名稱空間中不存在的變數 |
>>> xpleafTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name ‘xpleaf‘ is not defined |
ZeroDivisionError |
除數為零 |
>>> 1/0Traceback (most recent call last): File "<stdin>", line 1, in <module>ZeroDivisionError: integer division or modulo by zero |
SyntaxError |
Python解譯器語法錯誤 (唯一不是在運行時發生的異常,發生在編譯時間,Python解譯器無法把相關指令碼編譯為Python位元組代碼) |
>>> for File "<stdin>", line 1 for ^SyntaxError: invalid syntax |
IndexError |
請求的索引走出序列範圍 |
>>> aList = []>>> aList[0]Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: list index out of range |
KeyError |
請求一個不存在的字典關鍵字 |
>>> aDict = {‘name‘: ‘xpleaf‘, ‘love‘: ‘cl‘}>>> aDict[‘clyyh‘]Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: ‘clyyh‘ |
IOError |
輸入/輸出錯誤 (任何類型的I/O錯誤都會引發IOError異常) |
>>> f = open(‘xpleaf‘)Traceback (most recent call last): File "<stdin>", line 1, in <module>IOError: [Errno 2] No such file or directory: ‘xpleaf‘ |
AttributeError |
嘗試訪問未知的對象屬性 |
>>> class myClass(object):... pass... >>> myInst = myClass()>>> myInst.nameTraceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: ‘myClass‘ object has no attribute ‘name‘ |
本文出自 “香飄葉子” 部落格,請務必保留此出處http://xpleaf.blog.51cto.com/9315560/1762213
Python回顧與整理8:錯誤和異常