Python复习二(raise与assert函数)

1、raise函数

关键字raise是用来抛出异常的,一旦抛出异常后,后续的代码将无法运行。这实际上的将不合法的输出直接拒之门外,避免黑客通过这种试探找出我们程序的运行机制,从而找出漏洞,获得非法权限。

name="123"
raise NameError("invalid name")
NameError:invalid name
try:
   num=5/0
except:
   print("An Error occurred")
   raise

运行结果:

An Error occurred

ZeroDivisionError: division by zero

2、assert函数

python assert断言是声明其布尔值必须为真的判定,如果发生异常就说明表达示为假。可以理解assert断言语句为raise-if-not,用来测试表示式,其返回值为假,就会触发异常。

print("1")
assert 2+2==4
print("2")
assert 1+1==3
print("3")

运行结果:

1
2
AssertionError

猜你喜欢

转载自blog.csdn.net/uuuuu11/article/details/82591127