Python打卡学习第十天
今天是异常处理
异常就是一个事件,会在程序执行过程中有语法等错误时发生,影响程序的正常运行。
1、try-except语句
语法格式:
try:
[语句体]
except Exception[as reason ]:
出现异常(Rxception)后的处理代码
上图中文件 0.txt 不存在时,就抛出异常,并且输出了具体原因。
2、try-finally语句
语法格式:
try:
[语句体]
except Exception[as reason ]:
出现异常(Rxception)后的处理代码
finally:
无论如何都会被执行的代码
3、try-except-else
语法格式:
try:
[语句体]
except Exception[as reason ]:
出现异常(Rxception)后的处理
else:
没有异常后被执行的代码
4、try(with)-except语句
语法格式:
try:
with<语句> as name:
[语句体]
except Exception[as reason ]:
出现异常(Rxception)后的处理代码
抛出异常
主动抛出异常,使用关键字raise实现
语法格式如下:
raise Exception (defineexceptname)
Exception为异常名称
defineexceptname为自定义的异常描述