Day 9
异常 exception
异常处理结构:
try:
被监控的可能引发异常的语句块,跳过try块中异常以后的代码
except BaseException as e: # e 就是产生的异常对象
print(e) #打印异常对象
print(type(e))
>>> try:
... #被监控的可能引发异常的语句块,跳过try块中异常以后的代码
... print(3/0)
... except BaseException as e: # e 就是产生的异常对象
... print(e) #打印异常对象
... print(type(e))
...
division by zero
<class 'ZeroDivisionError'>
异常也是对象
>>> 3/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
try 多个except结构:
先子类后父类
所有异常的父类:BaseException --> Exception --> NameError, ValueError, AttributeError …
try…except…else:
如果有异常则执行except … ,如果没有则执行else
try…except…finally:
finally块无论是否发生异常都会被执行:用来释放try块中申请的资源
return语句处理异常结构:放最后
不要将return语句放到try,except,else,finally块中,会发生意想不到的错误,所以放最后
>>> def test_a():
... print("step1")
... try:
... x = 3/0
... except:
... print("step2")
... print("异常, 0不能做除数")
... finally:
... print("step3")
... print("step5")
... return "e"
...
>>> print(test_a())
step1
step2
异常, 0不能做除数
step3
step5
e
with 上下文管理:
释放资源
with context_expr as var:
不是用来取代try
>>> with open("d:/a.txt", "r") as f:
content = f.readline()
print(content)
>>> print("执行程序结束")
xxxxx
执行程序结束
traceback 追溯
用来打印一些异常信息
>>> import traceback
>>> try:
... print("step1")
... num = 10/0
... except:
... traceback.print_exc()
...
step1
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
ZeroDivisionError: division by zero
# 将异常信息输入到指定文件中:
import traceback
try:
print("step1")
num = 10/0
except:
with open("d:/a.txt", "a") as f: # a = append
traceback.print_exc(file=f)
raise抛出异常-自定义异常:
pycharm开发环境的调试
断点:程序运行到此处暂时挂起停止执行
在行号后面单击即可增加挂点