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]

 

相关文章:

  • 2022-12-23
  • 2021-07-14
  • 2022-02-20
  • 2022-12-23
  • 2021-07-29
  • 2021-05-27
  • 2022-12-23
  • 2021-05-11
猜你喜欢
  • 2022-12-23
  • 2021-11-27
  • 2022-01-09
  • 2022-01-04
  • 2022-01-02
  • 2021-09-15
相关资源
相似解决方案