使用try语句主要是为了进行异常的捕捉处理,异常在python也有几个基类
异常名称 | 描述 |
---|---|
BaseException | 所有异常的基类 |
SystemExit | 解释器请求退出 |
KeyboardInterrupt | 用户中断执行 |
Exception | 常规错误的基类 |
StopIteration | 迭代器没有更多的值 |
GeneratorExit | 生成器发生异常来通知退出 |
StandardError | 标准异常的基类 |
ArithmeticError | 数值计算错误的基类 |
FloatingPointError | 浮点计算错误的基类 |
OverflowError | 数值运算超出最大限制 |
ZeroDivisionError | 除零错误 |
AssertionError | 断言语句错误 |
#try的标准语句
try:
pass
except:
pass
else:
print ("try子句没有发生异常执行这里的语句")
finally:
print ("异常会不会发生都会执行")
##step1
1/0
D:\python\python.exe C:\Users\\demo.py
>>>> ZeroDivisionError: division by zero
#异常发生,触发ZeroDivisionError的基类异常并说明了原因
##step2
try:
1/0
except:
print ("hha")
D:\python\python.exe C:\Users\\demo.py
>>>> hha
# 捕捉到了异常触发异常打印hha
######################
try:
1/0
except NameError as e:
print ("hha",e)
D:\python\python.exe C:\Users\\demo.py
>>>> ZeroDivisionError: division by zero
# 触发了异常,但是异常只会进行捕捉NameError的异常类,所有except语句没有生效
######################
try:
1/0
except ZeroDivisionError as e:
print ("hha",e)
D:\python\python.exe C:\Users\\demo.py
>>>> hha division by zero
#触发了异常,异常捕捉ZeroDivisionError类,except语句触发打印内容
##step3
try:
1/0
except ZeroDivisionError as e:
print ("hha",e)
else:
print ("try ok")
finally:
print ("end")
D:\python\python.exe C:\Users\\demo.py
>>>>hha division by zero
>>>>end
# 触发了异常后打印异常并且最终还是执行了finally语句