鱼C论坛

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

[技术交流] 《零基础入门学习python》第三十二讲笔记:异常处理:你不可能总是对的

[复制链接]
发表于 2017-8-30 16:55:40 | 显示全部楼层 |阅读模式

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

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

x
Exception :异常

Assert:  断言:当Assert 后面条件为假时,自动抛出一个异常,为真则继续代码

  1. >>> my_list = ['小甲鱼是帅哥']
  2. >>> assert len(my_list) > 0
  3. >>> my_list.pop()
  4. '小甲鱼是帅哥'
  5. >>> assert len(my_list) > 0   # assert 后面条件为假,抛出AssertionError
  6. Traceback (most recent call last):
  7.   File "<pyshell#21>", line 1, in <module>
  8.     assert len(my_list) > 0
  9. AssertionError
复制代码

  1. >>> my_list.fishc   # 列表没有fishc方法
  2. Traceback (most recent call last):
  3.   File "<pyshell#22>", line 1, in <module>
  4.     my_list.fishc
  5. AttributeError: 'list' object has no attribute 'fishc'
复制代码

  1. >>> my_list = [1,2,3]
  2. >>> my_list[3]   # 此例索引没有3
  3. Traceback (most recent call last):
  4.   File "<pyshell#24>", line 1, in <module>
  5.     my_list[3]
  6. IndexError: list index out of range
  7. >>> my_list[2]
  8. 3
复制代码

  1. >>> my_dict = {'one':1,'two':2,'three':3}
  2. >>> my_dict['one']
  3. 1
  4. >>> my_dict['four']  # 此例,关键字没有four
  5. Traceback (most recent call last):
  6.   File "<pyshell#28>", line 1, in <module>
  7.     my_dict['four']
  8. KeyError: 'four'
  9. >>> my_dict.get('four')   # 用get方法取没有的键不会报错
复制代码
  1. >>> fishc  # 没有fishc这个变量
  2. Traceback (most recent call last):
  3.   File "<pyshell#30>", line 1, in <module>
  4.     fishc
  5. NameError: name 'fishc' is not defined
复制代码

  1. >>> print 'I love FishC.com'   # 语法错误
  2. SyntaxError: invalid syntax (<pyshell#31>, line 1)
复制代码
  1. >>> 1 + '1'  # 类型错误
  2. Traceback (most recent call last):
  3.   File "<pyshell#32>", line 1, in <module>
  4.     1 + '1'
  5. TypeError: unsupported operand type(s) for +: 'int' and 'str'
复制代码

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

>>>

评分

参与人数 1鱼币 +1 收起 理由
小甲鱼 + 1

查看全部评分

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-26 04:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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