Python基础–异常处理
作用
避免程序报错,提高程序的稳定性
获取报错信息
多用于可以预判的错误进行提前处理
1 | # 具体的模板 |
具体的实例
1 | try: |
Exception使用
- BaseException是所有类型的报错信息的基类
- Exception是常见类的报错信息
- error 会接受具体的报错信息
1
2
3
4
5
6
7
8
9
10try:
with open("file") as f:
content = f.read()
print(content)
except BaseException as error:
# BaseException是所有类型的报错信息的基类
# Exception是常见类的报错信息
# error 会接受具体的报错信息
print("报错信息是:%s" % error)
print("我到底执不执行呢?")try中else和finally的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15try:
# with open("file") as f:
# content = f.read()
# print(content)
# print("a")
f = open("a.txt")
content = f.read(f)
except BaseException as error:
print("报错信息是:%s" % error)
else:
# 尝试执行的代码没有对应的错误就会直接运行else里面的代码
print("你没有错,可以运行")
finally:
# finally的代码 无论是否错误缩进的内容都会被打印的
print("我是不管错误不错都会出来的")