assert 表示式 [, "斷言異常提示資訊"]
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: 無效值
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("捕獲成功")
捕獲成功
異常名稱 | 描述 |
---|---|
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 | 除(或取模)零錯誤 |