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 , in <module>
assert b <=
AssertionError
[Finished in .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 .1s]
05-11 20:03