Python之標準異常及常用異常實例

      在Python開發過程中,經常會遇到各種各樣的報錯情況,所以瞭解Python中的各種報錯就很有必要。小白最近整理了一下Python中經常遇到的報錯情況,並列舉了案例,如下表格,還有一些報錯情況,待嘗試~

AssertionError 斷言語句失敗:當 assert 關鍵字後的條件爲假時,程序運行會停止並拋出 AssertionError 異常 l1 = ['111a']
assert len(l1)>0
l2 = []
assert len(l2)>0
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-4-5d421c3e78d3> in <module>
      1 l2 = []
----> 2 assert len(l2)>0
IndexError 序列中沒有此索引(index):索引超出序列範圍會引發此異常 l1 = ['111a']
l1[1]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-130763729f9e> in <module>
      1 l1 = ['111a']
----> 2 l1[1]

IndexError: list index out of range
KeyError 映射中沒有這個鍵:字典中查找一個不存在的關鍵字時引發此異常 dict={'張三':"50"}
dict["李四"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-77ca0e0db50c> in <module>
      1 dict={'張三':"50"}
----> 2 dict["李四"]

KeyError: '李四'
AttributeError 對象沒有這個屬性:當試圖訪問的對象屬性不存在時拋出的異常 l1 = ['111a']
l1.len
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-f1db6a9cf562> in <module>
      1 l1 = ['111a']
----> 2 l1.len

AttributeError: 'list' object has no attribute 'len'
NameError 未聲明/初始化對象 (沒有屬性):嘗試訪問一個未聲明的變量時,引發此異常 l1 = ['111a']
l2 = []
l3
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-75536776ce4c> in <module>
      1 l1 = ['111a']
      2 l2 = []
----> 3 l3

NameError: name 'l3' is not defined
TypeError 對類型無效的操作:不同類型數據之間的無效操作 1+'aaa
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-9e5eb69813e3> in <module>
----> 1 1+'aaa'

TypeError: unsupported operand type(s) for +: 'int' and 'str'
ZeroDivisionError 除(或取模)零 (所有數據類型):除法運算中除數爲 0 引發此異常 a = 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-15-6c16767f6731> in <module>
----> 1 a = 1/0

ZeroDivisionError: division by zero
StopIteration 迭代器沒有更多的值 iterable = iter([1,2])
print(next(iterable))
print(next(iterable))
print(next(iterable))
1
2
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-16-0f9614553e6f> in <module>
      2 print(next(iterable))
      3 print(next(iterable))
----> 4 print(next(iterable))

StopIteration: 
ImportError 導入模塊/對象失敗 import sy
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-29-1afd4de6e860> in <module>
----> 1 import sy

ModuleNotFoundError: No module named 'sy'
SyntaxError Python 語法錯誤 for i in range(0,10)):
 File "<ipython-input-30-3edb23e8bd2e>", line 1
    for i in range(0,10)):
                        ^
SyntaxError: invalid syntax
ValueError 傳入無效的參數 #range方法的第三個參數不可爲0
for i in range(1, 3, 0):
    print (i)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-3663a22f4899> in <module>
----> 1 for i in range(1, 3, 0):
      2     print (i)

ValueError: range() arg 3 must not be zero
BaseException 所有異常的基類  
SystemExit 解釋器請求退出  
KeyboardInterrupt 用戶中斷執行(通常是輸入^C)  
Exception 常規錯誤的基類  
GeneratorExit 生成器(generator)發生異常來通知退出  
StandardError 所有的內建標準異常的基類  
ArithmeticError 所有數值計算錯誤的基類  
FloatingPointError 浮點計算錯誤  
OverflowError 數值運算超出最大限制  
EOFError 沒有內建輸入,到達EOF 標記  
EnvironmentError 操作系統錯誤的基類  
IOError 輸入/輸出操作失敗  
OSError 操作系統錯誤  
WindowsError 系統調用失敗  
LookupError 無效數據查詢的基類  
MemoryError 內存溢出錯誤(對於Python 解釋器不是致命的)  
UnboundLocalError 訪問未初始化的本地變量  
ReferenceError 弱引用(Weak reference)試圖訪問已經垃圾回收了的對象  
RuntimeError 一般的運行時錯誤  
NotImplementedError 尚未實現的方法  
IndentationError 縮進錯誤  
TabError Tab 和空格混用  
SystemError 一般的解釋器系統錯誤  
UnicodeError Unicode 相關的錯誤  
UnicodeDecodeError Unicode 解碼時的錯誤  
UnicodeEncodeError Unicode 編碼時錯誤  
UnicodeTranslateError Unicode 轉換時錯誤  
Warning 警告的基類  
DeprecationWarning 關於被棄用的特徵的警告  
FutureWarning 關於構造將來語義會有改變的警告  
OverflowWarning 舊的關於自動提升爲長整型(long)的警告  
PendingDeprecationWarning 關於特性將會被廢棄的警告  
RuntimeWarning 可疑的運行時行爲(runtime behavior)的警告  
SyntaxWarning 可疑的語法的警告  
UserWarning 用戶代碼生成的警告  

爲了更加系統的瞭解報錯的層級情況,下面列出Python中錯誤的層級結構,以下是 Python 內置異常類的層次結構:

BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
      +-- StopIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning
 

 

 

 

發佈了84 篇原創文章 · 獲贊 118 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章