鱼C论坛

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

[学习笔记] 032异常处理:你不可能总是对的

[复制链接]
发表于 2017-7-8 23:26:01 | 显示全部楼层 |阅读模式

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

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

x
1.AssertionError:断言语句(assert)失败
  1. >>> my_list = ['小甲鱼是帅哥']
  2. >>> assert len(my_list) > 0
  3. >>> my_list.pop()
  4. '小甲鱼是帅哥'
  5. >>> assert len(my_list) > 0
  6. Traceback (most recent call last):
  7.   File "<pyshell#3>", line 1, in <module>
  8.     assert len(my_list) > 0
  9. AssertionError
复制代码

2.AttributeError:尝试访问未知的对象属性
  1. >>> my_list.fishc
  2. Traceback (most recent call last):
  3.   File "<pyshell#4>", line 1, in <module>
  4.     my_list.fishc
  5. AttributeError: 'list' object has no attribute 'fishc'
复制代码

3.IndexError:索引超出序列范围
  1. >>> my_list = [1, 2, 3]
  2. >>> my_list[3]
  3. Traceback (most recent call last):
  4.   File "<pyshell#6>", line 1, in <module>
  5.     my_list[3]
  6. IndexError: list index out of range
  7. >>> my_list[2]
  8. 3
复制代码

4.KeyError:字典中查找一个不存在的关键字
  1. >>> my_dict = {'one':1, 'two':2, 'three':3}
  2. >>> my_dict['one']
  3. 1
  4. >>> my_dict['four']
  5. Traceback (most recent call last):
  6.   File "<pyshell#10>", line 1, in <module>
  7.     my_dict['four']
  8. KeyError: 'four'
复制代码

5.NameError:尝试访问一个不存在的变量
  1. >>> fishc
  2. Traceback (most recent call last):
  3.   File "<pyshell#11>", line 1, in <module>
  4.     fishc
  5. NameError: name 'fishc' is not defined
复制代码

6.OSError:操作系统产生的异常(例如打开一个不存在的文件)
  1. file_name = input('请输入需要打开的文件名:')
  2. f = open(file_name)
  3. print('文件的内容是:')
  4. for each_line in f:
  5. print(each_line)
  6. ========== RESTART: F:\BaiduYunDownload\《零基础入门学习Python》\py\032-1.py ==========
  7. 请输入需要打开的文件名:record
  8. Traceback (most recent call last):
  9.   File "F:\BaiduYunDownload\《零基础入门学习Python》\py\032-1.py", line 2, in <module>
  10.     f = open(file_name)
  11. FileNotFoundError: [Errno 2] No such file or directory: 'record'
复制代码

7.SyntaxError:Python的语法错误
  1. >>> print 'I love FishC.com'
  2. SyntaxError: Missing parentheses in call to 'print'
  3. >>> print('I love FishC.com')
  4. I love FishC.com
复制代码

8.TypeError:不同类型间的无效操作
  1. >>> 1 + '1'
  2. Traceback (most recent call last):
  3.   File "<pyshell#14>", line 1, in <module>
  4.     1 + '1'
  5. TypeError: unsupported operand type(s) for +: 'int' and 'str'
复制代码

9.ZeroDivisionError:除数为零
  1. >>> 5 / 0
  2. Traceback (most recent call last):
  3.   File "<pyshell#15>", line 1, in <module>
  4.     5 / 0
  5. ZeroDivisionError: division by zero
复制代码

评分

参与人数 1荣誉 +5 鱼币 +5 收起 理由
小甲鱼 + 5 + 5 支持楼主!

查看全部评分

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-5-4 07:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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