异常处理
.1常见的异常
下面这些都是类型class
严谨的程序应主动捕获并且处理这些异常
.2例子
在python中可以使用try except else finally raise等关键字来处理异常,使用方法如下:
异常类 | 执行的功能 |
---|---|
try | 后面跟着需要执行的语句 |
except | 捕获异常 并处理异常,通常异常有不同类型,可分别处理 |
else | 当try语句块正常执行时,无异常产生,执行else语句块 |
finally | 无论是否有异常产生,均执行 |
raise | 自定义异常 |
ZeroDivisionError
是一个类型,是Exception
的子类
def divide(a,b):
return a/b
while True:
sFirst = input('First number:')
sSecond = input('Second number:')
if sFirst == 'q' or sSecond == 'q':#输入q循环结束
break
try:
iFirst = int(sFirst)
iSecond = int(sSecond)
fResult = divide(iFirst,iSecond)
except (ZeroDivisionError) as e:
print('you can not divide by 0:',e)
except (ValueError,TypeError) as e:
print('illegal value been inputted:',e)
print(type(e))
except (Exception) as e:
print('an expection found, i dont know how to process it.')
raise#raise指这个异常自己处理不了,扔给外面处理
else:
print(sFirst,'/',sSecond,'=',fResult)
finally:
print('finally will be executed what ever happens.')
First number:1
Second number:3
1 / 3 = 0.3333333333333333
finally will be executed what ever happens.
First number:q
Second number:q