【Python3_基础系列_012】Python3-异常与断言
一、异常
python中对于异常的处理和其他语言的非常相似,
1.异常获取与处理:
try: suite1 #测试语句块 except exception1: suite2 #如果测试语句suite1中发生exception1异常时执行 except (exception2,exception3): suite3 #如果测试语句suite1中发生元组中任意异常时执行 except exception4 as reason: #as把异常的原因赋值给reason suite4 #如果测试语句suite1发生exception4的异常时执行 except: suite5 #如果测试语句suite1发生异常在所列出的异常之外时执行 else: suite5 #如果测试语句块suite1中没有发生异常时执行 finally: suit6 #不管测试语句suite1中又没有发生异常都会执行
2.自定义异常:
try: f = 'this is error 第%s行输入有误'%(4) raise Exception(f) #raise 抛出异常 自定义异常 print('22') except Exception as e: #这个e是局部的 print(e)
输出:this is error 第4行输入有误
这一行的输出是由最下面的print(e)输出的,因为自定了Exception,在except中将Exception as e. 所以print(e)打印的是自定义的异常信息。
二、断言
断言是对条件的判断,如果条件为真,继续执行。如果为假,中断程序,输出断言错误。
>>> assert 1==2 #断言错误,代码终止 Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> assert 1==2 AssertionError >>> assert 1==1 #断言正确,继续运行 >>>
三、面试题
异常和断言很少会有面试题,如果会问的话应该也是自定义异常的语句:
raise Exception(f)

浙公网安备 33010602011771号