python異常處理詳解

pythontab發表於2013-03-29

本節主要介紹Python中異常處理的原理和主要的形式。


1、什麼是異常


Python中用異常物件來表示異常情況。程式在執行期間遇到錯誤後會引發異常。如果異常物件並未被處理或捕獲,程式就會回溯終止執行。


2、丟擲異常


raise語句,raise後面跟上Exception異常類或者Exception的子類,還可以在Exception的括號中加入異常的資訊。


>>>raise Exception('message')


注意:Exception類是所有異常類的基類,我們還可以根據該類建立自己定義的異常類,如下:


class SomeCustomException(Exception): pass


3、捕捉異常(try/except語句)


try/except語句用來檢測try語句塊中的錯誤,從而讓except語句捕獲異常資訊並處理。


一個try語句塊中可以丟擲多個異常:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except ZeroDivisionError:
     print "The second number can't be zero!"
 except TypeError:
     print "That wasn't a number, was it?"


一個except語句可以捕獲多個異常:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except (ZeroDivisionError, TypeError, NameError):  #注意except語句後面的小括號
     print 'Your numbers were bogus...'

訪問捕捉到的異常物件並將異常資訊列印輸出:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except (ZeroDivisionError, TypeError), e:
     print e

捕捉全部異常,防止漏掉無法預測的異常情況:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except :
     print 'Someting wrong happened...'


4、else子句。除了使用except子句,還可以使用else子句,如果try塊中沒有引發異常,else子句就會被執行。

while 1:
     try:
         x = input('Enter the first number: ')
         y = input('Enter the second number: ')
         value = x/y
         print 'x/y is', value
     except:
         print 'Invalid input. Please try again.'
     else:
         break


上面程式碼塊執行後使用者輸入的x、y值合法的情況下將執行else子句,從而讓程式退出執行。

5、finally子句。不論try子句中是否發生異常情況,finally子句肯定會被執行,也可以和else子句一起使用。finally子句常用在程式的最後關閉檔案或網路套接字。

try:
     1/0
 except:
     print 'Unknow variable'
 else:
     print 'That went well'
 finally:
     print 'Cleaning up'

6、異常和函式

如果異常在函式內引發而不被處理,它就會傳遞到函式呼叫的地方,如果一直不被處理,異常會傳遞到主程式,以堆疊跟蹤的形式終止。

def faulty():
    raise Exception('Someting is wrong!')
def ignore_exception():
    faulty()
     
def handle_exception():
    try:
        faulty()
    except Exception, e:
        print 'Exception handled!',e
 
handle_exception() 
ignore_exception()

在上面的程式碼塊中,函式handle_exception()在呼叫faulty()後,faulty()函式丟擲異常並被傳遞到handle_exception()中,從而被try/except語句處理。而ignare_exception()函式中沒有對faulty()做異常處理,從而引發異常的堆疊跟蹤。

注意:條件語句if/esle可以實現和異常處理同樣的功能,但是條件語句可能在自然性和可讀性上差一些。