异常处理
什么是异常
异常是发生错误的信号,一旦程序出现错误,并且程序没有处理这种错误,那就会抛出异常,并且程序终止
错误分类
- 语法错误
- 逻辑错误
语法错误
- SyntaxError
语法错误就是不符合python基本的语法要求的,这种错误会直接导致程序无法运行,所以必须在程序运行前进行改正
>>> print"haha"
SyntaxError: invalid syntax
>>> if True
SyntaxError: invalid syntax
逻辑错误
常见的逻辑错误
- TypeError
>>> for i in 6:
pass
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
for i in 6:
TypeError: 'int' object is not iterable
- KeyError
>>> k = {
"Age":18,"Name":"YOHO"}
>>> k["school"]
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
k["school"]
KeyError: 'school'
- NameError
>>> name
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
name
NameError: name 'name' is not defined
- IndexError
>>