Python: 異常類型

概述

本文整理和參考自以下兩篇博文:

Python異常處理和異常類型
python 異常類型(比較全)

異常類型

排序 名稱 描述
A ArithmeticError 所有數值計算錯誤的基類
AssertionError 斷言語句失敗
AttributeError 對象沒有這個屬性
B BaseException 所有異常的基類
D DeprecationWarning 關於被棄用的特徵的警告
E EnvironmentError 操作系統錯誤的基類
EOFError 沒有內建輸入,到達EOF 標記
Exception 常規錯誤的基類
F FloatingPointError 浮點計算錯誤
FutureWarning 關於構造將來語義會有改變的警告
G GeneratorExit 生成器(generator)發生異常來通知退出
I ImportError 導入模塊/對象失敗
IndentationError 縮進錯誤
IndexError 序列中沒有沒有此索引(index)【越界】
IOError 輸入/輸出操作失敗
K KeyboardInterrupt 用戶中斷執行(通常是輸入^C)
KeyboardInterrupt 用戶中斷執行(通常是輸入^C)
KeyError 映射中沒有這個鍵
L LookupError 無效數據查詢的基類
M MemoryError 內存溢出錯誤(對於Python 解釋器不是致命的)
N NameError 未聲明/初始化對象 (沒有屬性)
NotImplementedError 尚未實現的方法
O OSError 操作系統錯誤
OverflowError 數值運算超出最大限制
OverflowWarning 舊的關於自動提升爲長整型(long)的警告
P PendingDeprecationWarning 關於特性將會被廢棄的警告
R ReferenceError 弱引用(Weak reference)試圖訪問已經垃圾回收了的對象
RuntimeError 一般的運行時錯誤
RuntimeWarning 可疑的運行時行爲(runtime behavior)的警告
S StandardError 所有的內建標準異常的基類
StopIteration 迭代器沒有更多的值
SyntaxError Python 語法錯誤
SyntaxWarning 可疑的語法的警告
SystemError 一般的解釋器系統錯誤
SystemExit 解釋器請求退出
SystemExit Python 解釋器請求退出
T TabError Tab 和空格混用
TypeError 對類型無效的操作
U UnboundLocalError 訪問未初始化的本地變量
UnicodeDecodeError Unicode 解碼時的錯誤
UnicodeEncodeError Unicode 編碼時錯誤
UnicodeError Unicode 相關的錯誤
UnicodeTranslateError Unicode 轉換時錯誤
UserWarning 用戶代碼生成的警告
V ValueError 傳入無效的參數
W Warning 警告的基類
WindowsError 系統調用失敗
Z ZeroDivisionError 除(或取模)零 (所有數據類型)

捕獲異常

python2.x

try:
	...some functions...
except Exception, e:
	print(e)

python3.x

try:
	...some functions...
except Exception as e:
	print(e)

常見錯誤舉例

NameError

嘗試訪問一個未申明的變量

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

ZeroDivisionError

  • 除數爲0 *
>>> v = 1/0
ZeroDivisionError: int division or modulo by zero

SyntaxError

語法錯誤

int int
SyntaxError: invalid syntax (<pyshell#14>, line 1)

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

KeyError

字典關鍵字不存在

Dic = {'1':'yes', '2':'no'}
>>> Dic['3']
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    Dic['3']
KeyError: '3'

IOError

輸入輸出錯誤

>>> f = open('abc')
IOError: [Errno 2] No such file or directory: 'abc'

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'

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'

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

AssertionError

斷言錯誤

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

NotImplementedError

方法沒實現引起的異常

class Base(object):
    def __init__(self):
        pass

    def action(self):
        #拋出異常,說明該接口方法未實現
        raise NotImplementedError

LookupError

鍵、值不存在引發的異常

是IndexError、KeyError的基類, 如果你不確定數據類型是字典還是列表時,可以用LookupError捕獲此異常

StandardError

標準異常

除StopIteration, GeneratorExit, KeyboardInterrupt 和SystemExit外,其他異常都是StandarError的子類。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章