一常见异常
1.AssertionError
断言语句(assert)失败,示例如下:
>>> a = 1
>>> assert(a<1)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
assert(a<1)
AssertionError
2.IndexError
索引越界,导致索引错误
>>> list1 = [1,2,3]
>>> list1[3]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
list1[3]
IndexError: list index out of range
3.keyError
引用字典中不存在的key
>>> dict1={'1':'one','2':'two','3':'three'}
>>> dict1['4']
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
dict1['4']
KeyError: '4'
4.TypeError
类型异常
>>> 1 + '1'
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
1 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
5.ZeroDivisionError
0被当着被除数的错误
>>> 5/0
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
5/0
ZeroDivisionError: division by zero
二 捕获异常 try-catch
运行期检测到的错误被称为异常。为了防止异常出现导致程序中断,可增加异常处理try-catch语句块
try:
检测范围
catch Except:
出现异常(Exception)的代码处理
2.1文件不存在
2.1.1 当打开一个文件时,可能会出现文件不存在,示例代码如下:
f = open("nihao.txt")
print(f.read())
f.close()
===== RESTART: D:\sources\python\python\05exception_file.py ====
Traceback (most recent call last):
File "D:\sources\python\pytho\05exception_file.py", line 1, in <module>
f = open("nihao.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'nihao.txt'
2.1.2 对可能抛异常的代码块,添加try-catch语句块后,报错信息比较友好
try:
f = open("nihao.txt")
print(f.read())
f.close()
except OSError:
print('文件出错了')
>>>
===== RESTART: D:\sources\python\python\05exception_file.py ====
文件出错了
2.1.3 抛出异常信息
try:
f = open("nihao.txt")
print(f.read())
f.close()
except OSError as reason:
print('文件出错了\n错误原因是:' + str(reason) )
===== RESTART: D:\sources\python\python\05exception_file.py ====
文件出错了
错误原因是:[Errno 2] No such file or directory: 'nihao.txt'
2.2 多个异常处理
多个异常的处理,当第二行报错时,直接跳转到第二个捕获异常的语句块
try:
sum = 1 + '1'
f = open("nihao.txt")
print(f.read())
f.close()
except OSError as reason:
print('文件出错了\n错误原因是:' + str(reason) )
except TypeError as reason:
print('类型错误',reason)
===== RESTART: D:\sources\python\python\05exception_file.py ====
类型错误 unsupported operand type(s) for +: 'int' and 'str'
另外一种写法
try:
sum = 1 + '1'
f = open("nihao.txt")
print(f.read())
f.close()
except(OSError,TypeError) as reason:
print('出错了\n错误原因是:' + str(reason) )
-----------------------
===== RESTART: D:\sources\python\python\05exception_file.py ====
出错了
错误原因是:unsupported operand type(s) for +: 'int' and 'str'
try-finally
finally用于关闭文件,不加finally语句块,写入的‘你好啊’不会保存到文件中;示例如下
try:
f = open("nihao.txt",'w')
print(f.write('你好啊'))
sum = 1 + '1'
f.close()
except(OSError,TypeError) as reason:
print('出错了\n错误原因是:' + str(reason) )
finally:
f.close()