1.基础模块-异常类
raise 语句格式为:
raise [exceptionName [(reason)]]
异常情况
常见的几种异常情况类别:
- AssertionError
- 当 assert 断言条件结果为假时(False),程序运行会停止并抛出 AssertionError 异常
>>> demo_list = ['C语言中文网']
>>> assert len(demo_list) > 0
>>> demo_list.pop()
'C语言中文网'
>>> assert len(demo_list) > 0
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
assert len(demo_list) > 0
AssertionError
- AttributeError
- 当访问的对象属性不存在时抛出异常
>>> demo_list = ['C语言中文网']
>>> demo_list.len
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
demo_list.len
AttributeError: 'list' object has no attribute 'len'
- IndexError
- 索引超出序列范围会引发异常
>>> demo_list = ['C语言中文网']
>>> demo_list[3]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
demo_list[3]
IndexError: list index out of range
- KeyError
- 字典中缺失key值
>>> demo_dict={'C语言中文网':"c.biancheng.net"}
>>> demo_dict["C语言"]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
demo_dict["C语言"]
KeyError: 'C语言'
- NameError
- 访问一个未声明的变量,引发异常
>>> C语言中文网
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
C语言中文网
NameError: name 'C语言中文网' is not defined
- TypeError
- 不同类型数据之间的错误操作
>>> 1+'C语言中文网'
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
1+'C语言中文网'
TypeError: unsupported operand type(s) for +: 'int' and 'str'