python 異常處理總結_python

來源:互聯網
上載者:User

       最近,做個小項目經常會遇到Python 的異常,讓人非常頭疼,故對異常進行整理,避免下次遇到異常不知所措,以下就是對Python 異常進行的整理。

1.Python異常類 

 

異常 描述
NameError 嘗試訪問一個沒有申明的變數
ZeroDivisionError 除數為0
SyntaxError 語法錯誤
IndexError 索引超出序列範圍
KeyError 請求一個不存在的字典關鍵字
IOError 輸入輸出錯誤(比如你要讀的檔案不存在)
AttributeError 嘗試訪問未知的對象屬性
ValueError 傳給函數的參數類型不正確,比如給int()函數傳入字元

 2.捕獲異常

Python完整的捕獲異常的語句有點像:

try: try_suiteexcept Exception1,Exception2,...,Argument: exception_suite...... #other exception blockelse: no_exceptions_detected_suitefinally: always_execute_suite

額...是不是很複雜?當然,當我們要捕獲異常的時候,並不是必須要按照上面那種格式完全寫下來,我們可以丟掉else語句,或者finally語句;甚至不要exception語句,而保留finally語句。額,暈了?好吧,下面,我們就來一一說明啦。

2.1 try...except...語句

 try_suite不消我說大家也知道,是我們需要進行捕獲異常的代碼。而except語句是關鍵,我們try捕獲了程式碼片段try_suite裡的異常後,將交給except來處理。

 try...except語句最簡單的形式如下:

try: try_suiteexcept: exception block  

  上面except子句不跟任何異常和異常參數,所以無論try捕獲了任何異常,都將交給except子句的exception block來處理。如果我們要處理特定的異常,比如說,我們只想處理除零異常,如果其他異常出現,就讓其拋出不做處理,該怎麼辦呢?這個時候,我們就要給except子句傳入異常參數啦!那個ExceptionN就是我們要給except子句的異常類(請參考異常類那個表格),表示如果捕獲到這類異常,就交給這個except子句來處理。比如:

try: try_suiteexcept 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/intnumexcept 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:fjiaError:you must input a float num![root@Cherish tmp]# python test.py Please input a float:0.9999Error:you must input a float num which is large or equal then 1![root@Cherish tmp]# python test.py Please input a float:25.0914

  上面的例子大家一看都懂,就不再解釋了。只要大家明白,我們的except可以處理一種異常,多種異常,甚至所有異常就可以了。

    大家可能注意到了,我們還沒解釋except子句後面那個Argument是什麼東西?別著急,聽我一一道來。這個Argument其實是一個異常類的執行個體(別告訴我你不知到什麼是執行個體),包含了來自異常代碼的診斷資訊。也就是說,如果你捕獲了一個異常,你就可以通過這個異常類的執行個體來擷取更多的關於這個異常的資訊。例如:

>>> try:...  1/0... except ZeroDivisionError,reason:...  pass... >>> type(reason)<type 'exceptions.ZeroDivisionError'>>>> print reasoninteger division or modulo by zero>>> reasonZeroDivisionError('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'

上面這個例子,我們捕獲了除零異常,但是什麼都沒做。那個reason就是異常類ZeroDivisionError的執行個體,通過type就可以看出。

2.2 try ... 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!

我們可以看到,如果assert後面的運算式為真,則什麼都不做,如果不為真,就會拋出AssertionErro異常,而且我們傳進去的字串會作為異常類的執行個體的具體資訊存在。其實,assert異常也可以被try塊捕獲:

>>> 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.Contex 

thread.LockType 

threading.Lock 

threading.RLock 

threading.Condition 

threading.Semaphore 

threading.BoundedSemaphore

至於什麼是上下文管理協議,如果你不只關心怎麼用with,以及哪些對象可以使用with,那麼我們就不比太關心這個問題

4.拋出異常(raise)

如果我們想要在自己編寫的程式中主動拋出異常,該怎麼辦呢?raise語句可以協助我們達到目的。其基本文法如下:

raise [SomeException [, args [,traceback]] 
第一個參數,SomeException必須是一個異常類,或異常類的執行個體

第二個參數是傳遞給SomeException的參數,必須是一個元組。這個參數用來傳遞關於這個異常的有用資訊。

第三個參數traceback很少用,主要是用來提供一個跟中記錄對(traceback)
下面我們就來列舉幾個 例子:

>>> raise NameErrorTraceback (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> #追蹤記錄對象

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.