除0运算 - ZeroDivisionError
1/0
division by zero
找不到文件 - FileNotFoundError
with open(“tmp.txt”) as f:
pass
No such file or directory: ‘tmp.txt’
值错误 - ValueError
传入一个调用者不期望的值,即使这个值的类型是正确的
s = “1.6”
n = int(s)
invalid literal for int() with base 10: ‘1.6’
索引错误 - IndexError
ls = [0,1,2,3]
ls[5]
list index out of range
类型错误 - TypeError
传入对象类型与要求不符
2 + “3”
unsupported operand type(s) for +: ‘int’ and ‘str’
名称错误 - NameError
使用一个未被定义的变量
print(a)
NameError : name ‘a’ is not defined
键错误 - KeyError
试图访问字典里不存在的键
d = {}
d[“m”]
KeyError: ‘m’
当异常发生的时候,如果不预先设定处理方法,程序就会中断
目的:提高程序的稳定性和可靠性
单分支
x, y = 5, 0
try:
z = x / y
except ZeroDivisionError:
print('0不可以被除')
多分支
d = {'name': 'Tom'}
try:
d['height']
except NameError:
print('变量名不存在')
except KeyError:
print('键不存在')
万能异常Exception
d = {'name': 'Tom'}
try:
d['height']
except Exception:
print('出错了')
捕获异常的值as
d = {'name': 'Tom'}
try:
d['height']
except Exception as e:
print(e)
try顺利执行,则else也执行
try:
with open('tmp.csv') as f:
text = f.read()
except FileNotFoundError:
print('找不到该文件')
else:
print('找到了该文件')
无论try执行与否,finally都执行
d = {'name': 'Tom'}
try:
d['height']
except Exception as e:
print(e)
finally:
print('无论是否出发异常,都将执行')