Python assert例外處理(一看即懂)

2020-07-16 10:05:24
Python 還支援斷言語法。在一套程式完成之前,程式設計者並不知道程式可能會在哪裡報錯,或是觸發何種條件的報錯,因此使用斷言語法可以有效地做好異常檢測,並適時觸發和丟擲異常。

Python 中使用 assert 語句宣告斷言,其語法為:

assert 表示式 [, "斷言異常提示資訊"]


Python 首先檢測表示式結果是否為 True,若為 True 則繼續向下執行,否則將觸發斷言異常,並顯示斷言異常提示資訊,後續程式碼捕獲該異常並做進一步處理。例如:
def testAssert(x):
    assert x < 1,'無效值'
    print ("有效值")
testAssert(1)
上述程式碼的執行結果如下所示:

>>> def testAssert(x):
...          assert x < 1,'無效值'
...          print ("有效值")

>>> testAssert(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    testAssert(1)
  File "<stdin>", line 2, in testAssert
    assert x < 1,'無效值'
AssertionError: 無效值


可見,當 assert 語句判斷的表示式結果為 False 時觸發了斷言異常,此時可以使用 try…except 語句捕獲並做進一步處理,例如:
def testAssert(x):
    assert x < 1, '無效值'
    print("有效值")
try:
    testAssert(1)
except Exception:
    print("捕獲成功")
上述程式碼的執行結果如下所示:

>>> def testAssert(x):
...          assert x < 1, '無效值'
...          print("有效值")
   
>>> try:
...         testAssert(1)
...     except Exception:
...         print("捕獲成功")
   
捕獲成功


Python直譯器內建的預定義標準異常如表 1 所示。
表 1:Python 直譯器內建的預定義標準異常
異常名稱 描述
ArithmeticError 所有數值計算錯誤的基礎類別
AssertionError 斷言語句失敗
AttributeError 物件無此屬性
BaseException 所有異常的基礎類別
DeprecationWarning 關於被棄用的特徵的警告
EnvironmentError 作業系統相關的錯誤的基礎類別
EOFError 到達檔案尾(EOF, End-of-File)錯誤
Exception 常規錯誤的基礎類別
FloatingPointError 浮點計算錯誤
FutureWarning 關於將來語意會有改變的警告
GeneratorExit 生成器發生異常通知退出
ImportError 引入模組/物件失敗
IndentationError 縮排錯誤
IndexError 序列中無此索引
IOError 輸入/輸出操作失敗
Keyboardlnterrupt 使用者中斷執行
KeyError 對映中無此鍵
LookupError 無效資料查詢的基礎類別
MemoryError 記憶體溢位錯誤
NameError 未宣告/初始化物件,名稱呼叫錯誤
NotImplementedError 尚未實現的方法
OSError 作業系統錯誤
OverflowError 數值運算超出最大限制
PendingDeprecationWarning 關於特性將會被廢棄的警告
ReferenceError 弱參照試圖存取已經被回收的物件
RuntimeError 一般執行時錯誤
RuntimeWarning 執行時行為警告
StandardError 所有內建標準異常的基礎類別
StopIteration 疊代器沒有更多的值
SyntaxError Python語法錯誤
SyntaxWarning 語法警告
SystemError 一般的直譯器系統錯誤
SystemExit 直譯器請求退出
TabError Tab和空格混用
TypeError 對型別無效的操作
UnboundLocalError 存取未初始化的本地變數
UnicodeDecodeError Unicode解碼錯誤
UnicodeEncodeError Unicode編碼錯誤
UnicodeError Unicode相關錯誤
UnicodeTranslateError Unicode轉換錯誤
UserWarning 使用者程式碼生成的警告
ValueError 傳入無效引數
Warning 各種警告的基礎類別
WindowsError 系統呼叫失敗
ZeroDivisionError 除(或取模)零錯誤