首頁  >  文章  >  後端開發  >  python異常處理詳解

python異常處理詳解

高洛峰
高洛峰原創
2016-10-20 09:46:301310瀏覽

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


1、什麼是異常


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


2、拋出異常


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


>>>raise Exception('message')


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

class SomeCustomException(Exception): pass

3、捕捉異常(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?"

   


一個被存取的語句可以捕捉到多個異常:異常物件並將異常訊息列印輸出:

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

   

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

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

   


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

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

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

   


6、異常和函數

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

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

   

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

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn