使用python处理文件时,不能确保文件内的数据类型是否正确,可以使用try-except语句
来确保程序处理所有文件,而不是在报错的位置终止,try-except语句
简单代码示例如下:
except
使用Exception
可以捕获所有异常,完全保障程序的运行。
lst = [12, 546, 496, 123, 88]
for i in range(7):
try:
print(lst[i])
except IndexError as e: # IndexError 捕获索引异常
print(e)
except Exception as e: # Exception 捕获所有异常
print(e)
print(f"列表长度为{len(lst)},当前索引值为{i}")
>>>
12
546
496
123
88
list index out of range
list index out of range
注释掉IndexError
,异常会被Exception
捕获,此时输出为
>>>
12
546
496
123
88
list index out of range
列表长度为5,当前索引值为5
list index out of range
列表长度为5,当前索引值为6