异常处理
1.AssertionError 断言语句(assert)失败
>>> list1=['小甲鱼']
>>> assert len(list1)>0
>>> list1.pop()
'小甲鱼'
>>> assert len(list1)>0
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
assert len(list1)>0
AssertionError
2.AttributeError 尝试访问未知的对象属性
>>> list1.fishc
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
list1.fishc
AttributeError: 'list' object has no attribute 'fishc'
3.IndexError 索引超出序列的范围
>>> list1=[1,2,3]
>>> list1[3]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
list1[3]
IndexError: list index out of range
4.KeyError 字典中查找一个不存在的关键字
>>> dict1={'one':1,'two':2,'three':3}
>>> dict1['two']
2
>>> dict1['four']
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
dict1['four']
KeyError: 'four'
>>> dict1.get('four')
5.NameError 尝试访问一个不存在的变量
>>> fish
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
fish
NameError: name 'fish' is not defined
6.OSError 操作系统产生的异常(例如打开一个不存在的文件)
7.SyntaxError Python的语法错误
8.TypeError 不同类型间的无效操作
9.ZeroDivisionError 除数为零
10.异常检测
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码
finally:
无论如何都会被执行的代码
try:
sum=1+'1'
f=open('我是一个文件.txt')
print(f.read())
f.close()
except OSError as reason:
print('文件出错啦!\n错误的原因是:'+str(reason))
except TypeError as reason:
print('类型出错啦!\n错误的原因是:'+str(reason))
try:
f=open('我是一个文件.txt')
print(f.read())
sum=1+'1'
except(OSError,TypeError):
print('出错啦!')
finally:
f.close()
11.raise 引发异常
>>> raise
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
raise
RuntimeError: No active exception to reraise
>>> 1/0
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
1/0
ZeroDivisionError: division by zero
>>> raise ZeroDivisionError
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
raise ZeroDivisionError
ZeroDivisionError
>>> raise ZeroDivisionError('除数为零的异常')
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
raise ZeroDivisionError('除数为零的异常')
ZeroDivisionError: 除数为零的异常