【Python之旅】第四篇(二):Pyt
- 2020 年 1 月 10 日
- 筆記
在Python程式的執行過程中,難免會出現異常的情況,如果做的是跟用戶交互的程式,當用戶輸入不可接受的內容時,在可預見的範圍內,我們當然是希望可以給用戶一些提示,而不是原來Python內置異常中的那些提示語句,畢竟那些語句只適合給程式設計師做調試參考,對用戶並沒有多大的價值。因此這就需要了解Python的常見異常了。
當然,我們也可以製作自己的異常,當用戶輸入滿足或不滿足我們的需求時,就可以觸發這些異常,以使我們寫的程式更加人性化。
1.Python常見異常與演示
Python常見異常可列舉如下:
常見異常 |
中文解釋 |
---|---|
IOError |
輸入/輸出異常;基本上是無法打開文件 |
ImportError |
無法引入模組或包;基本上是路徑問題或名稱錯誤 |
IndexError |
下標索引超出序列邊界,比如當x只有三個元素,卻試圖訪問x[5] |
KeyError |
試圖訪問字典里不存在的鍵 |
NameError |
使用一個還未被賦予對象的變數 |
IndentationError |
語法錯誤(的子類) ;程式碼沒有正確對齊 |
SyntaxError |
Python程式碼非法,程式碼不能編譯 |
KeyboardInterrupt |
Ctrl+C被按下 |
EOFError |
Ctrl+D被按下 |
UnboundLocalError |
試圖訪問一個還未被設置的局部變數,基本上是由於另有一個同名的全局變數,導致你以為正在訪問它 |
AttributeError |
試圖訪問一個對象沒有的屬性,比如myInst.foo,但是myInst沒有屬性foo |
ValueError |
傳入一個調用者不期望的值,即使值的類型是正確的 |
TypeError |
傳入對象類型與要求的不符合 |
對常見的異常,做如下的簡單演示:
IOError:輸入/輸出異常
>>> f = file('myfile.txt') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: 'myfile.txt'
ImportError:無法引入模組或包
>>> import xpleaf Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named xpleaf
IndexError:下標索引超出序列邊界
>>> a = range(3) >>> a [0, 1, 2] >>> a[3] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
KeyError:試圖訪問字典里不存在的鍵
>>> mydict={'name':'xpleaf'} >>> mydict['age'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'age'
NameError:使用一個還未被賦予對象的變數
>>> print xpleaf Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'xpleaf' is not defined
IndentationError:語法錯誤(的子類) ;程式碼沒有正確對齊
>>> for i in range(3): ... print i ... print 'Error!' File "<stdin>", line 3 print 'Error!' ^ IndentationError: unexpected indent
SyntaxError:Python程式碼非法,程式碼不能編譯
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python Error.py File "Error.py", line 3 prin kd ^ SyntaxError: invalid syntax >>> for File "<stdin>", line 1 for ^ SyntaxError: invalid syntax
KeyboardInterrupt:Ctrl+C被按下
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py name:^CTraceback (most recent call last): File "test.py", line 2, in <module> name = raw_input('name:') KeyboardInterrupt
EOFError:Ctrl+D被按下
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python EOF.py name:Traceback (most recent call last): File "EOF.py", line 2, in <module> name = raw_input('name:') EOFError
UnboundLocalError:試圖訪問一個還未被設置的局部變數
程式程式碼如下: name = 'xpleaf' def sayYourName(mark): if mark == 1: name = 'yonghaoye' else: print 'My name is:',name sayYourName(0) 執行情況如下: xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py My name is: Traceback (most recent call last): File "test.py", line 10, in <module> sayYourName(0) File "test.py", line 8, in sayYourName print 'My name is:',name UnboundLocalError: local variable 'name' referenced before assignment 注意:如果是sayYourName(1),則不會出現問題,此時相當於在函數中定義了一個局部變數
AttributeError:試圖訪問一個對象沒有的屬性,比如myInst.foo,但是myInst沒有屬性foo
>>> class myClass(): ... pass ... >>> myInst = myClass() >>> myInst.bar = 'spam' >>> myInst.bar 'spam' >>> myInst.foo Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: myClass instance has no attribute 'foo'
ValueError:傳入一個調用者不期望的值,即使值的類型是正確的
>>> f = file('myfile.txt','io') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: mode string must begin with one of 'r', 'w', 'a' or 'U', not 'io'
TypeError:傳入對象類型與要求的不符合
>>> num = 3 >>> str = 'name' + num + 'age' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects
2.Python異常捕捉
知道了常見的Python異常,就有需要對這些異常進行捕捉了,主要是使用:try…except語句進行異常的捕捉。
簡單演示一個異常的捕捉,假設這裡要捕捉的異常為IndexError:
程式碼如下: try: a = [1, 2, 3] a[3] except IndexError: print '