Python回顧與整理8:錯誤和異常

來源:互聯網
上載者:User

標籤:錯誤   異常   python   異常處理   異常捕獲   

0.說明


        如果想寫出使用者體驗高的代碼,那麼就需要考慮到在執行自己寫的這段代碼中在和使用者互動的過程中可能會出現的問題,也就是說,需要對可能出現的異常進行處理,只有做好這些工作,才能寫出使用者體驗好的代碼。



1.什麼是異常


  • 錯誤

        錯誤是文法(導致解譯器無法解釋)或邏輯(也就是代碼品質問題)上的,在Python中,當檢測到錯誤時,解譯器會指出當前流無法繼續執行下去,於是就出現了異常。

  • 異常

        程式出現了錯誤而在正常控制流程以外採取的行為。

        根據上面的解釋,可以理解為,只要解譯器檢測到程式運行時出現了錯誤(與Python解譯器不相容而導致),就會觸發一個異常。



2.Python中的異常


        如下:

異常類型 描述 簡單例子
NameError 嘗試訪問一個未聲明的變數,或者是在名稱空間中不存在的變數
>>> xpleafTraceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name ‘xpleaf‘ is not defined
ZeroDivisionError 除數為零
>>> 1/0Traceback (most recent call last):  File "<stdin>", line 1, in <module>ZeroDivisionError: integer division or modulo by zero
SyntaxError

Python解譯器語法錯誤

(唯一不是在運行時發生的異常,發生在編譯時間,Python解譯器無法把相關指令碼編譯為Python位元組代碼)

>>> for  File "<stdin>", line 1    for      ^SyntaxError: invalid syntax
IndexError 請求的索引走出序列範圍
>>> aList = []>>> aList[0]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range
KeyError 請求一個不存在的字典關鍵字
>>> aDict = {‘name‘: ‘xpleaf‘, ‘love‘: ‘cl‘}>>> aDict[‘clyyh‘]Traceback (most recent call last):  File "<stdin>", line 1, in <module>KeyError: ‘clyyh‘
IOError

輸入/輸出錯誤

(任何類型的I/O錯誤都會引發IOError異常)

>>> f = open(‘xpleaf‘)Traceback (most recent call last):  File "<stdin>", line 1, in <module>IOError: [Errno 2] No such file or directory: ‘xpleaf‘
AttributeError 嘗試訪問未知的對象屬性
>>> class myClass(object):...   pass... >>> myInst = myClass()>>> myInst.nameTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: ‘myClass‘ object has no attribute ‘name‘





本文出自 “香飄葉子” 部落格,請務必保留此出處http://xpleaf.blog.51cto.com/9315560/1762213

Python回顧與整理8:錯誤和異常

相關文章

聯繫我們

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