python学习之assert语句

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:UsershuangrongDesktop	est.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]
原文地址:https://www.cnblogs.com/leomei91/p/7660256.html