1、常见异常的产生

1)除0运算——ZeroDivisionError
2)找不到可读文件——FileNotFoundError
3)值错误——ValueError
4)索引错误——IndexError
5)类型错误——TypeError
6)变量名错误——NameError

2、异常的处理

1)try_except
  ① 单分支

1
2
3
4
5
6
x = 10
y = 0
try:
z = x/y
except ZeroDivisionError:
print("0不能作除数")

  ② 多分支

1
2
3
4
5
6
7
8
9
10
ls = []
d = {"name":"LC"}
try:
d["age"]
except NameError:
print("变量名不存在")
except IndexError:
print("索引超出界限")
except KeyError:
print("键不存在")

  ③ 万能异常 Exception

1
2
3
4
5
6
ls = []
d = {"name":"LC"}
try:
d["age"]
except Exception:
print("出错了")

  ④ 捕获异常的值 as

1
2
3
4
5
6
7
ls = []
d = {"name":"LC"}
try:
y = m
d["age"]
except Exception as e: # 获取错误的值
print(e)

2)try_except_else

1
2
3
4
5
6
7
try:
with open("try.txt") as f:
text = f.read()
except FileNotFoundError:
print("找不到文件")
else:
print("找到了")

3)try_except_finally:无论try模块是否执行,finally最后都会执行

1
2
3
4
5
6
7
8
9
10
ls = []
d = {"name":"LC"}
try:
y = x
ls[3]
d["age"]
except Exception as e: # 获取错误的值
print(e)
finally:
print("执行finally")