14.7 �获所有异常¶

问题¶

怎样�获代�中的所有异常?

解决方案¶

想��获所有的异常,�以直接�获 Exception ��:

try:
   ...
except Exception as e:
   ...
   log('Reason:', e)       # Important!

这个将会�获除了 SystemExit � KeyboardInterrupt 和 GeneratorExit 之外的所有异常。 如果你还想�获这三个异常,将 Exception 改� BaseException ��。

讨论¶

�获所有异常通常是由于程�员在�些���作中并�能记�所有�能的异常。 如果你�是很细心的人,这也是编写�易调试代�的一个简�方法。

正因如此,如果你选择�获所有异常,那么在�个地方(比如日志文件�打�异常到�幕)打�确切原因就比较��了。 如果你没有这样�,有时候你看到异常打�时�能摸��头脑,就�下�这样:

def parse_int(s):
    try:
        n = int(v)
    except Exception:
        print("Couldn't parse")

试��行这个函数,结果如下:

>>> parse_int('n/a')
Couldn't parse
>>> parse_int('42')
Couldn't parse
>>>

这时候你就会挠头想:“这咋回事啊?� �如你�下�这样�写这个函数:

def parse_int(s):
    try:
        n = int(v)
    except Exception as e:
        print("Couldn't parse")
        print('Reason:', e)

这时候你能获�如下输出,指明了有个编程错误:

>>> parse_int('42')
Couldn't parse
Reason: global name 'v' is not defined
>>>

很明显,你应该尽�能将异常处�器定义的精准一些。 �过,�是你必须�获所有异常,确�打�正确的诊断信�或将异常传播出去,这样�会丢失掉异常。