15.python異常處理

來源:互聯網
上載者:User

標籤:怎樣   無法   pac   int()   sdi   直接   bsp   col   不同   

異常:程式運行時報錯

關於異常處理:

  程式員編訂特定編碼,用來捕捉異常,這段代碼與與程式邏輯沒有關係,只和異常處理相關。捕捉成功則進入另一處理分支,執行為其定製的邏輯,使程式不會發生崩潰

1.使用if判斷式:
num1=input(‘>>: ‘) #輸入一個字串試試if num1.isdigit():    int(num1) #我們的正統程式放到了這裡,其餘的都屬於異常處理範疇elif num1.isspace():    print(‘輸入的是空格,就執行我這裡的邏輯‘)elif len(num1) == 0:    print(‘輸入的是空,就執行我這裡的邏輯‘)else:    print(‘其他情情況,執行我這裡的邏輯‘)

總結:  

  if判斷式的異常處理只能針對某一段代碼,對於不同程式碼片段的相同類型還需要重複if進行處理

  頻繁使用if會導致程式本身可讀性變差

  if是能解決異常的只是存在上述問題

2.選用py特定文法:

1.基本文法

try:     被檢測的代碼塊except 異常類型:     try中一旦檢測到異常,就執行這個位置的邏輯

2.異常只能處理指定的異常情況,如果非指定異常則無法處理

# 未捕獲到異常,程式直接報錯s1 = ‘hello‘try:    int(s1)except IndexError as e:    print(e)

3.萬能異常:Exception可以捕獲任意異常

s1 = ‘hello‘try:    int(s1)except Exception as e:    print(e)---invalid literal for int() with base 10: ‘hello‘# 它不會飄紅,但是也會顯示相關錯誤

 如果相對任何異常都統一丟棄,那麼一個Exception就足夠了

如果想要對不同的異常定製不同的處理邏輯,則需要多分支處理

s1 = ‘hello‘try:    float(s1)except IndexError as e:    print(e)except KeyError as e:    print(e)except ValueError as e:    print(e)

4.其他組織機構

s1 = ‘hello‘try:    int(s1)except IndexError as e:    print(e)except KeyError as e:    print(e)except ValueError as e:    print(e)#except Exception as e:#    print(e)else:    print(‘try內代碼塊沒有異常則執行我‘)finally:    print(‘無論異常與否,都會執行該模組,通常是進行清理工作‘)    # 這步不管怎樣最後都會執行

5.主動觸發異常

try:    raise TypeError(‘類型錯誤‘)except Exception as e:    print(e)

 

15.python異常處理

相關文章

聯繫我們

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