python異常處理詳解

來源:互聯網
上載者:User
本節主要介紹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可以實現和異常處理同樣的功能,但是條件陳述式可能在自然性和可讀性上差一些。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.