您的位置:首页 > 编程语言 > Python开发

python 之异常Exception 1

2018-03-26 11:07 363 查看
一、什么是异常:
file_name = input('请输入需要打开的文件名:')
f = open(file_name)
print('文件的内容是:')
for each in f:
print(each)#结果报错:FileNotFoundError: [Errno 2] No such file or directory: 'fff'
i = 9/0#ZeroDivisionError: division by zero
二、python标准异常总结 http://bbs.fishc.com/thread-45814-1-1.html #AssertionError 断言语句(assert)失败
list1 = [123]
assert len(list1)>0#不会报错
list1.pop()#list1中没有元素了
assert len(list1)>0#结果:报错AssertionError
#AttributeError 尝试访问未知的对象属性(python中包含一个变量名都是一个对象)
#新建对象
list1 = [123]
list1.cout()#列表不存在cout方法,因此报错AttributeError: 'list' object has no attribute 'cout'
#IndexError:索引的值超出了序列的范围
list1 = [1,2,3]
list1[3]#结果报错:IndexError: list index out of range
#keyError 字典中查找一个不存在的关键字
dict1 = {'one':1,'two':2}
print(dict1['one'])#结果:1
print(dict1['onene'])#报错:KeyError: 'onene'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: