Minimalist Python learning tutorial -----Exception handling (assert, try, except)

1. Assert

assert 1==1    # 条件为 true 正常执行
assert 1==2    # 条件为 false 触发异常

Insert picture description here

2、try … exception … else … finally

try:
	此处是需要检测的代码
except:
	此处是try模块代码出现异常后需要执行的代码
else:
	如果try不报错,则执行该处代码,和except模块是互斥关系
finally:
	此处是无论如何都要执行的代码

Examples are as follows:

try:
    a = 5/1
except:
    print('程序出错')
else:
    print('a的值是:', a)
finally:
    print('成功')

The results of the operation are as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_28057379/article/details/115243120