1、NameError:嘗試訪問一個未申明的變量
>>> v
NameError: name 'v' is not defined
2、ZeroDivisionError:除數為0
>>> v = 1/0
ZeroDivisionError: int division or modulo by zero
3、SyntaxError:語法錯誤
>>> int int
SyntaxError: invalid syntax (<pyshell#14>, line 1)
4、IndexError:索引超出范圍
>>> List = [2]
>>> List[3]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
List[3]
IndexError: list index out of range
5、KeyError:字典關鍵字不存在
>>> Dic = {'1':'yes', '2':'no'}
>>> Dic['3']
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
Dic['3']
KeyError: '3'
6、IOError:輸入輸出錯誤
>>> f = open('abc')
IOError: [Errno 2] No such file or directory: 'abc'
7、AttributeError:訪問未知對象屬性
>>> class Worker:
def Work():
print("I am working")
>>> w = Worker()
>>> w.a
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
w.a
AttributeError: 'Worker' object has no attribute 'a'
8、ValueError:數值錯誤
>>> int('d')
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
int('d')
ValueError: invalid literal for int() with base 10: 'd'
9、TypeError:類型錯誤
>>> iStr = '22'
>>> iVal = 22
>>> obj = iStr + iVal;
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
obj = iStr + iVal;
TypeError: Can't convert 'int' object to str implicitly
10、AssertionError:斷言錯誤
>>> assert 1 != 1
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
assert 1 != 1
AssertionError
以上轉自http://blog.csdn.net/fcoolx/article/details/4202872
下面增加一些本人工作過程中遇到過的異常:
11、MemoryError:內存耗盡異常
12、NotImplementedError:方法沒實現引起的異常
示例:
1 class Base(object): 2 def __init__(self): 3 pass 4 5 def action(self): 6 raise NotImplementedError
定義一個類,一個接口方法action,如果直接調用action則拋NotImplementedError異常,這樣做的目的通常是用來模擬接口
13、LookupError:鍵、值不存在引發的異常
LookupError異常是IndexError、KeyError的基類
如果你不確定數據類型是字典還是列表時,可以用LookupError捕獲此異常
14、StandardError 標准異常。
除StopIteration, GeneratorExit, KeyboardInterrupt 和SystemExit外,其他異常都是StandarError的子類。
異常處理有別於錯誤檢測:
錯誤檢測與異常處理區別在於:錯誤檢測是在正常的程序流中,處理不可預見問題的代碼,例如一個調用操作未能成功結束
