yespython 发表于 2018-5-4 10:17:07

python异常

一、什么是异常:

file_name = input('请输入需要打开的文件名:')
f = open(file_name)
print('文件的内容是:')
for each in f:
    print(each)#结果报错:FileNotFoundError: 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 =
assert len(list1)>0#不会报错
list1.pop()#list1中没有元素了
assert len(list1)>0#结果:报错AssertionError

#AttributeError 尝试访问未知的对象属性(python中包含一个变量名都是一个对象)
#新建对象
list1 =
list1.cout()#列表不存在cout方法,因此报错AttributeError: 'list' object has no attribute 'cout'

#IndexError:索引的值超出了序列的范围
list1 =
list1#结果报错:IndexError: list index out of range

#keyError 字典中查找一个不存在的关键字
dict1 = {'one':1,'two':2}
print(dict1['one'])#结果:1
print(dict1['onene'])#报错:KeyError: 'onene'
页: [1]
查看完整版本: python异常