python進階(5)異常模塊

異常模塊

下面介紹python經常使用的異常模塊
 python

AttributeError異常

AttributeError試圖訪問一個類中不存在的成員(包括:成員變量、屬性和成員方法)而引起的異常shell

AttributeError:'Animal' object has no attribute 'age'

 

OSError異常

OSError是操做系統相關異常操作系統

FileNotFoundError:[Error 2] No such file or directory: 'abc.txt'

 

IndexError異常

IndexError異常是訪問序列元素時,下標索引超出取值範圍所引起的異常code

IndexError: list index out of range

 

KeyError異常

KeyError異常是試圖訪問字典裏不存在的鍵時而引起的異常索引

>>> dict[104]
Traceback(most recent call last):
    File"<pyshell#14>", line1, in <module>
        dict1[104]
KeyError: 104

 

NameError異常

NameError是試圖使用一個不存在的變量而引起的異常it

NameError: name 'value1' is not defined

 

TypeError異常

TypeError是試圖傳入變量類型與要求的不符合時而發生的異常ast

>>> i = '2'
>>> print(5 / i)
Traceback(most recent call last):
    File"<pyshell#20>", line1, in <module>
        print(5 / i)
TypeError: unsupported operand type(s) for /: 'int' and 'str'

 

ValueError異常

ValueError異常是因爲傳入一個無效的參數值而引起的異常變量

>>> i = 'QWE
>>> print(5 / int(i))
Traceback(most recent call last):
    File"<pyshell#22>", line1, in <module>
        print(5 / int(i))
ValueError: invalid literal for int() with base 10: 'QWE'
相關文章
相關標籤/搜索