8.1 基本概念
先来看几个示例。
>>> x, y = 10, 5
>>> a = x / y
>>> print(A) # 拼写错误
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
print(A)
NameError: name 'A' is not defined
>>> 10 * (1 / 0) # 除 0 错误
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
10 * (1 / 0)
ZeroDivisionError: division by zero
>>> 4 + span * 3 # 使用未定义变量
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
4 + span * 3
NameError: name 'span' is not defined
>>> '2' + 2 # 对象类型不支持特定的操作
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
'2' + 2
TypeError: can only concatenate str (not "int") to str
异常处理指因为程序执行过程中出错而在正常控制流之外采取的行动。当 Python 检测到一个错误时,解释器就会指出当前程序无法再执行下去,就出现了异常。
尽管异常处理机制非常重要非常有效,但不建议使用异常代替常规检查。应避免过多依赖异常处理机制来提高程序健壮性。
8.2 Python 异常类与自定义异常
Python 内异常的继承层次。

097D490E190A836610E31F7F1A38FAB5.jpg
如果需要可以继承 Python 内置异常类来实现自定义的异常类。
class ShortInputException(Exception):
''' 自定义异常类 '''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = input('请输入-->')
if len(s) < 3:
raise ShortInputException(len(s), 3)
except EOFError:
print('你输入了一个结束标记')
except ShortInputException as x:
print('ShortInputException: 输入的长度是 %d, 长度至少是:%d'%(x.length, x.atleast))
else:
print('没有异常发生')