鱼C论坛

 找回密码
 立即注册
查看: 3045|回复: 0

[学习笔记] python异常

[复制链接]
发表于 2018-5-4 10:17:07 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一、什么是异常:

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'
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-15 00:44

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表