Python中的異常類型

來源:互聯網
上載者:User

1、NameError:嘗試訪問一個未申明的變數

>>> v
NameError: name 'v' is not defined

2、ZeroDivisionError:除數為0
>>> v = 1/0
ZeroDivisionError: int division or modulo by zero

3、SyntaxError:語法錯誤
>>> int int
SyntaxError: invalid syntax (<pyshell#14>, line 1)

4、IndexError:索引超出範圍
>>> List = [2]
>>> List[3]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
List[3]
IndexError: list index out of range

5、KeyError:字典關鍵字不存在
>>> Dic = {'1':'yes', '2':'no'}
>>> Dic['3']
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
Dic['3']
KeyError: '3'

6、IOError:輸入輸出錯誤
>>> f = open('abc')
IOError: [Errno 2] No such file or directory: 'abc'

7、AttributeError:訪問未知對象屬性
>>> class Worker:
def Work():
print("I am working")

>>> w = Worker()
>>> w.a
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
w.a
AttributeError: 'Worker' object has no attribute 'a'

8、ValueError:數值錯誤
>>> int('d')
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
int('d')
ValueError: invalid literal for int() with base 10: 'd'

9、TypeError:類型錯誤
>>> iStr = '22'
>>> iVal = 22
>>> obj = iStr + iVal;
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
obj = iStr + iVal;
TypeError: Can't convert 'int' object to str implicitly

10、AssertionError:斷言錯誤
>>> assert 1 != 1
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
assert 1 != 1
AssertionError

相關文章

聯繫我們

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