python 基礎---異常處理

來源:互聯網
上載者:User

標籤:print   檔案   ima   代碼塊   info   exe   font   工作   bsp   

程式一旦發生錯誤,就從錯誤的位置停下來了,不在繼續執行後面的內容
使用try和except就能處理異常
1 try:2      被檢測的代碼塊3 except 異常類型:4      try中一旦檢測到異常,就執行這個位置的邏輯
try
我們需要處理的代碼

except
  • 後面跟一個錯誤類型 當代碼發生錯誤且錯誤類型符合的時候 就會執行except中的代碼
  • 支援多分支
Exception
  • 萬能的處理機制
  • 有了萬能的處理機制仍然需要把能預測到的問題單獨處理
  • 單獨處理的所有內容都應該寫在萬能異常之前
else 
沒有異常的時候執行else中的代碼


finally
  • 不管代碼是否異常,都會執行
  • 常用於檔案、資料庫等關閉
  • finally和return相遇的時候 依然會執行
  • 函數裡做異常處理用,不管是否異常去做一些收尾工作
舉例:
1 ret = int(input(‘number:‘))2 print(ret)

 處理1:(except 後面跟一個錯誤類型 當代碼發生錯誤且錯誤類型符合的時候 就會執行except中的代碼

1 try:2     ret = int(input(‘number:‘))3     print(ret)4 except ValueError:5     print("請輸入數字")

處理2:(Exception萬能處理,不需要錯誤類型

1 try:2     ret = int(input(‘number:‘))3     print(ret)4 except Exception:5     print("請輸入數字")

處理3:

1 try:2     ret = int(input(‘number:‘))3     print(ret)4 except Exception as error:5     print(‘你錯了,老鐵‘,error)

處理4:(多分支)

 1 s1 = ‘hello‘ 2 try: 3     int(s1) 4 except IndexError as e: 5     print(e) 6 except KeyError as e: 7     print(e) 8 except ValueError as e: 9     print(e)10 except Exception as e:11     print(e)

處理5:(else和finally)

 1 s1 = ‘hello‘ 2 try: 3     int(s1) 4 except IndexError as e: 5     print(e) 6 except KeyError as e: 7     print(e) 8 except ValueError as e: 9     print(e)10 #except Exception as e:11 #    print(e)12 else:13     print(‘try內代碼塊沒有異常則執行我‘)14 finally:15     print(‘無論異常與否,都會執行該模組,通常是進行清理工作‘)

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.