1.常见异常
'''AssertionError:断言语句失败。当assert这个关键字后面的条件为False时,程序将停止并抛出AssertionError异常。assert语句一般是在测试程序的时候用于在代码中置入检查点'''
>>> a = ['lzm']
>>> assert len(a) > 0
>>> a.pop()
'lzm'
>>> assert len(a) > 0
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
assert len(a) > 0
AssertionError
'''AttributeError:尝试访问未知的对象属性。当试图访问的对象属性不存在时抛出AttributeError异常'''
>>> a = []
>>> a.lzm()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a.lzm()
AttributeError: 'list' object has no attribute 'lzm'
'''IndexError:索引超出序列的范围'''
>>> a = [1, 1, 1]
>>> a[3]
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
a[3]
IndexError: list index out of range
'''KeyError:字典中查找一个不存在的关键字。建议使用dict.get()方法'''
>>> a = {'a':1, 'b':2, 'c':3}
>>> a['a']
1
>>> a['d']
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
a['d']
KeyError: 'd'
'''NameError:尝试访问一个不存在的变量'''
>>> b
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
b
NameError: name 'b' is not defined
'''OSError:操作系统产生的异常。FileNotFoundError是OSError的子类'''
>>> f = open('qqqq')
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
f = open('qqqq')
FileNotFoundError: [Errno 2] No such file or directory: 'qqqq'
'''SyntaxError:Python的语法错误'''
>>> print'acs'
SyntaxError: invalid syntax
'''TypeError:不同类型间的无效操作,例如类型不同的对象是不能相互进行计算的'''
>>> 1+'1'
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
1+'1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
'''ZeroDivisionError:除数为零'''
>>> 1 / 0
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
1 / 0
ZeroDivisionError: division by zero
异常捕获可以使用try语句实现,任何出现在try语句范围内的异常都会被即使捕获到。
2.try-except
|