python異常處理--try except else raise finally

來源:互聯網
上載者:User

標籤:auth   img   info   條件   col   .com   cep   strong   png   

寫程式時遇到異常情況,程式可能無法正常運行。此時就需要引入異常處理

1.try ...except

try 後面寫正常啟動並執行程式碼,except即為異常情況

 1 a=3 2 b=2 3 for i in range(5): 4     try: 5         a = a - 1 6         c=b/a 7         print(c) 8  9     except Exception as e:10         print(e)#輸出異常行為名稱

結果顯示如下,異常行為的名稱為(division by zero)

2.try ....except...else 語句,當沒有異常發生時,else中的語句將會被執行

a=3b=2for i in range(3):    try:        a = a - 1        c=b/a        print(c)    except Exception as e:        print(e)    else:        print("正常運行")

發生異常時,else的語句沒有被運行

3.

當執行try ...finally 語句時,無論異常是否發生,在程式結束前,finally中的語句都會被執行。

#Author:wang yuea=3b=2for i in range(3):    try:        a = a - 1        c=b/a        print(c)    except Exception as e:        print(e)    else:        print("正常運行")    finally:        print("finally")

4.raise引發一個異常,比如,當一個條件不滿足使用者意願時引發一個異常

a=3if a<4:    raise Exception
else: print(a)

 

python異常處理--try except else raise finally

聯繫我們

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