1.Python異常類
Python是面向對象語言,所以程序拋出的異常也是類。常見的Python異常有以下幾個,大家只要大致掃一眼,有個映像,等到編程的時候,相信大家肯定會不只一次跟他們照面(除非你不用Python了)。
異常 | 描述 |
NameError | 嘗試訪問一個沒有申明的變量 |
ZeroDivisionError | 除數為0 |
SyntaxError | 語法錯誤 |
IndexError | 索引超出序列范圍 |
KeyError | 請求一個不存在的字典關鍵字 |
IOError | 輸入輸出錯誤(比如你要讀的文件不存在) |
AttributeError | 嘗試訪問未知的對象屬性 |
ValueError | 傳給函數的參數類型不正確,比如給int()函數傳入字符串形 |
2.捕獲異常
Python完整的捕獲異常的語句有點像:
- try:
- try_suite
- except Exception1,Exception2,...,Argument:
- exception_suite
- ...... #other exception block
- else:
- no_exceptions_detected_suite
- finally:
- always_execute_suite
2.1.try...except...語句
try_suite不消我說大家也知道,是我們需要進行捕獲異常的代碼。而except語句是關鍵,我們try捕獲了代碼段try_suite里的異常后,將交給except來處理。
try...except語句最簡單的形式如下:
- try:
- try_suite
- except:
- exception block
- try:
- try_suite
- except Exception:
- exception block
- >>> try:
- ... res = 2/0
- ... except ZeroDivisionError:
- ... print "Error:Divisor must not be zero!"
- ...
- Error:Divisor must not be zero!
看,我們真的捕獲到了ZeroDivisionError異常!那如果我想捕獲並處理多個異常怎么辦呢?有兩種辦法,一種是給一個except子句傳入多個異常類參數,另外一種是寫多個except子句,每個子句都傳入你想要處理的異常類參數。甚至,這兩種用法可以混搭呢!下面我就來舉個例子。
- try:
- floatnum = float(raw_input("Please input a float:"))
- intnum = int(floatnum)
- print 100/intnum
- except ZeroDivisionError:
- print "Error:you must input a float num which is large or equal then 1!"
- except ValueError:
- print "Error:you must input a float num!"
- [root@Cherish tmp]# python test.py
- Please input a float:fjia
- Error:you must input a float num!
- [root@Cherish tmp]# python test.py
- Please input a float:0.9999
- Error:you must input a float num which is large or equal then 1!
- [root@Cherish tmp]# python test.py
- Please input a float:25.091
- 4
大家可能注意到了,我們還沒解釋except子句后面那個Argument是什么東西?別着急,聽我一一道來。這個Argument其實是一個異常類的實例(別告訴我你不知到什么是實例),包含了來自異常代碼的診斷信息。也就是說,如果你捕獲了一個異常,你就可以通過這個異常類的實例來獲取更多的關於這個異常的信息。例如:
- >>> try:
- ... 1/0
- ... except ZeroDivisionError,reason:
- ... pass
- ...
- >>> type(reason)
- <type 'exceptions.ZeroDivisionError'>
- >>> print reason
- integer division or modulo by zero
- >>> reason
- ZeroDivisionError('integer division or modulo by zero',)
- >>> reason.__class__
- <type 'exceptions.ZeroDivisionError'>
- >>> reason.__class__.__doc__
- 'Second argument to a division or modulo operation was zero.'
- >>> reason.__class__.__name__
- 'ZeroDivisionError'
2.2try ... except...else語句
現在我們來說說這個else語句。Python中有很多特殊的else用法,比如用於條件和循環。放到try語句中,其作用其實也差不多:就是當沒有檢測到異常的時候,則執行else語句。舉個例子大家可能更明白些:
- >>> import syslog
- >>> try:
- ... f = open("/root/test.py")
- ... except IOError,e:
- ... syslog.syslog(syslog.LOG_ERR,"%s"%e)
- ... else:
- ... syslog.syslog(syslog.LOG_INFO,"no exception caught\n")
- ...
- >>> f.close()
2.3 finally子句
finally子句是無論是否檢測到異常,都會執行的一段代碼。我們可以丟掉except子句和else子句,單獨使用try...finally,也可以配合except等使用。
例如2.2的例子,如果出現其他異常,無法捕獲,程序異常退出,那么文件 f 就沒有被正常關閉。這不是我們所希望看到的結果,但是如果我們把f.close語句放到finally語句中,無論是否有異常,都會正常關閉這個文件,豈不是很 妙
- >>> import syslog
- >>> try:
- ... f = open("/root/test.py")
- ... except IOError,e:
- ... syslog.syslog(syslog.LOG_ERR,"%s"%e)
- ... else:
- ... syslog.syslog(syslog.LOG_INFO,"no exception caught\n")
- ... finally:
- >>> f.close()
3.兩個特殊的處理異常的簡便方法
3.1斷言(assert)
什么是斷言,先看語法:
- assert expression[,reason]
其中assert是斷言的關鍵字。執行該語句的時候,先判斷表達式expression,如果表達式為真,則什么都不做;如果表達式不為真,則拋出異常。reason跟我們之前談到的異常類的實例一樣。不懂?沒關系,舉例子!最實在!
- >>> assert len('love') == len('like')
- >>> assert 1==1
- >>> assert 1==2,"1 is not equal 2!"
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- AssertionError: 1 is not equal 2!
- >>> try:
- ... assert 1 == 2 , "1 is not equal 2!"
- ... except AssertionError,reason:
- ... print "%s:%s"%(reason.__class__.__name__,reason)
- ...
- AssertionError:1 is not equal 2!
- >>> type(reason)
- <type 'exceptions.AssertionError'>
3.2.上下文管理(with語句)
如果你使用try,except,finally代碼僅僅是為了保證共享資源(如文件,數據)的唯一分配,並在任務結束后釋放它,那么你就有福了!這個with語句可以讓你從try,except,finally中解放出來!語法如下:
- with context_expr [as var]:
- with_suite
- >>> with open('/root/test.py') as f:
- ... for line in f:
- ... print line
上面這幾行代碼干了什么?
(1)打開文件/root/test.py
(2)將文件對象賦值給 f
(3)將文件所有行輸出
(4)無論代碼中是否出現異常,Python都會為我們關閉這個文件,我們不需要關心這些細節。
這下,是不是明白了,使用with語句來使用這些共享資源,我們不用擔心會因為某種原因而沒有釋放他。但並不是所有的對象都可以使用with語句,只有支持上下文管理協議(context management protocol)的對象才可以,那哪些對象支持該協議呢?如下表:
file
decimal.Context
thread.LockType
threading.Lock
threading.RLock
threading.Condition
threading.Semaphore
threading.BoundedSemaphore
至於什么是上下文管理協議,如果你不只關心怎么用with,以及哪些對象可以使用with,那么我們就不比太關心這個問題:)
4.拋出異常(raise)
如果我們想要在自己編寫的程序中主動拋出異常,該怎么辦呢?raise語句可以幫助我們達到目的。其基本語法如下:
- raise [SomeException [, args [,traceback]]
第二個參數是傳遞給SomeException的參數,必須是一個元組。這個參數用來傳遞關於這個異常的有用信息。
第三個參數traceback很少用,主要是用來提供一個跟中記錄對象(traceback)
下面我們就來舉幾個例子。
- >>> raise NameError
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- NameError
- >>> raise NameError() #異常類的實例
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- NameError
- >>> raise NameError,("There is a name error","in test.py")
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- >>> raise NameError("There is a name error","in test.py") #注意跟上面一個例子的區別
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- NameError: ('There is a name error', 'in test.py')
- >>> raise NameError,NameError("There is a name error","in test.py") #注意跟上面一個例子的區別
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- NameError: ('There is a name error', 'in test.py')
5.異常和sys模塊
另一種獲取異常信息的途徑是通過sys模塊中的exc_info()函數。該函數回返回一個三元組:(異常類,異常類的實例,跟中記錄對象)
- >>> try:
- ... 1/0
- ... except:
- ... import sys
- ... tuple = sys.exc_info()
- ...
- >>> print tuple
- (<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('integer division or modulo by zero',), <traceback object at 0x7f538a318b48>)
- >>> for i in tuple:
- ... print i
- ...
- <type 'exceptions.ZeroDivisionError'> #異常類
- integer division or modulo by zero #異常類的實例
- <traceback object at 0x7f538a318b48> #跟蹤記錄對象