assert語句用於代碼檢測並報警。
語法
assert code...
例子
# -*- coding: utf-8 -*-
# assert語句說明
a,b= 1,23
a == 2
assert b >=21
assert b <=22
結果
Traceback (most recent call last): File "C:\Users\huangrong\Desktop\test.py", line 7, in <module> assert b <=22 AssertionError [Finished in 0.1s]
分析
"a == 2"錯了,但並沒有報錯,因為沒有使用assert。
"b <=22"報錯了!因為使用了assert。
常用的處理錯誤方式
# -*- coding: utf-8 -*-
# assert語句說明
a,b= 1,23
try:
assert a == 2
except Exception as e:
print('hello')
說明: Exception表示捕獲所有異常。
執行結果
hello [Finished in 0.1s]