python異常處理詳解

dfee 9年前發布 | 18K 次閱讀 Python Python開發

本節主要介紹Python中異常處理的原理和主要的形式。1、什么是異常Python中用異常對象來表示異常情況。程序在運行期間遇到錯誤后會引發異常...

本節主要介紹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()</pre>

在上面的代碼塊中,函數handle_exception()在調用faulty()后,faulty()函數拋出異常并被傳遞到handle_exception()中,從而被try/except語句處理。而ignare_exception()函數中沒有對faulty()做異常處理,從而引發異常的堆棧跟蹤。

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


</div>

 本文由用戶 dfee 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!