异常处理
常见的异常处理
AssertionError;断言语句失败
assert在测试程序的时候 在代码植入检查点
>>> my_list = ["tianjun"]
>>> assert len(my_list) > 0
>>> my_list.pop()
'tianjun'
>>>
>>> assert len(my_list) > 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
就是说assert len(my_list)>0这个语句判断为假时会报错
因为my_list只有“tianjun”这个字符串,pop()弹出后my_list为空,下面assert等式不成立,所以抛出异常
attributeerror尝试访问未知的对象属性
>>> my_list = []
>>> my_list.fisa
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'fisa'
indexerror索引超出序列范围
>>> my_list = [1,2,3,4,5]
>>> my_list[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
keyerror字典中查找一个不存在的关键词
>>> dict1 = {"one":"1","two":"2","three":"3"}
>>> dict1['one']
'1'
>>> dict1['six']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'six'
>>>
nameerror尝试访问一个不存在的变量
>>> name = {}
>>> name
{}
>>> not name
True
>>> mett
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'mett' is not defined
OSerror操作系统异常
syntaxerror语法错误
>> print"wocao,meiyou xioakuohao"
File "<stdin>", line 1
print"wocao,meiyou xioakuohao"
^
SyntaxError: invalid syntax
typeerror不同类型的无效操作
>>> 1 + '1'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
zerodivisionerror除数为零
>>> 5/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
try-except语句
try-except语法
try:
检测范围
except exception[as reason]:
出现异常(esception)后处理代码
用于检测和处理异常
>>> try:
... f = open("一个文档.txt")
... print(f.read())
... f.close()
... except OSError:
... print("领绕我错了,报错了")
...
领绕我错了,报错了
>>>
根据不同的异常设置多个except
>>> try:
... sum = 1 + "1"
... f = open("wocao.txt")
... print(f.read())
... f.close()
... except OSError as reason:
... print("文件出错了,原因是"+str(reason))
... except TypeError as reason:
... print("文件出错了,原因是"+str(reason))
...
文件出错了,原因是unsupported operand type(s) for +: 'int' and 'str'
>>>
else语句(补充)
与if搭配的条件判断(要么怎样,要么不怎样)
if:
条件为真执行
else:
条件为假时执行
还能和for与while搭配如
>>> def showmaxdactor(num):
... count = num//2
... while count > 1:
... if num % count == 0:
... print('%d最大的数是%d' % (num,count))
... break
... count -=1
... else:
... print("%d是个素数"% num)
... num = int(input("请输入一个数"))
... showmaxdactor(num)
...
>>> showmaxdactor(2)
2是个素数
请输入一个数2
这个很好理解,要求用户输入的数的最大的约数。
也可以和异常处理进行搭配
>>> try:
... int('abx')
... except ValueError as reason:
... print("出错了"+ str(reason))
... else:
... print('没有异常')
...
出错了invalid literal for int() with base 10: 'abx'
>>>
with简洁你的异常处理
普通版
>>> try:
... f = open("date.txt",'w')
... for each_line in f:
... print(each_line)
... except OSError as reason:
... print("出错了:" + str(reason))
... finally:#这里的finally确保无论如和都是要被执行的
... f.close()
...
出错了:not readable
with版
>>> try:
... with open('date.txt','w')as f:
... for each_line in f:
... print(each_line)
... except OSError as reason:
... print("出错了"+str(reason))
...
出错了not readable
余总赠书,名额有限,还不上车
知识回顾 常见的异常: Exception 所有异常的基类(当不知道具体的异常可用这个处理)
AssertionError assert语句失败
AttributeError 特性应用或赋值时引发(试图访问一个对象没有的属性)
IOError 试图打开不存在的文件或者无全新的文件等操作时,就会引发(输入输入异常,基本是无法打开文件)
ImportError 无法引入模块或包,基本是路径问题
IndexError 在使用系列中不存在的索引时引发(下标索引超出序列边界)
KeyError 试图访问你字典里不存在的键key
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个未被赋予对象的变量
SyntaxError Python代码逻辑语法出错不能执行
TypeError 传入的对象类型与要求不符
UnboundLocalError 试图访问一个还未被设置的全局变量,基本上是由于另有一个同名的全局变量
ValueError 传入一个不被期望的值,即使类型正确
ZeroDivisonError 在除数为零发生的一个异常