什么是这个无特色的Python异常?

JAL*_*JAL 1 python exception python-2.6

我在Python 2.6上有一个包含与此类似的部分的脚本:

import sys

list_id='cow'
prev=[0,'cow']

try:
    if list_id==prev[1]:
        print '{0} is the same as {1}'.format(list_id,prev[1])
        sys.exit(0)
except:
    print 'exception occurred, exiting with error'
    sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

我注意到虽然它打印的是"相同"的行,但它也会记录异常!

如果删除try/except块,则解释器不会显示错误.如果捕获到ValueError之类的特定错误,则不执行except块.

import sys

list_id='cow'
prev=[0,'cow']

try:
    if list_id==prev[1]:
        print '{0} is the same as {1}'.format(list_id,prev[1])
        sys.exit(0)
except Exception as k:
    print 'exception occurred, exiting with error. Exception is:'
    print k.args
    sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

不执行except块,并且该过程以返回码0结束.因此,异常在层次结构中的异常之上?

import sys

list_id='cow'
prev=[0,'cow']

try:
    if list_id==prev[1]:
        print '{0} is the same as {1}'.format(list_id,prev[1])
        sys.exit(0)
except BaseException as k:
    print 'exception occurred, exiting with error. Exception is:'
    print k.args
    sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

产生

牛与牛发生异常是一样的,退出时有错误.
例外是:(0,)

并且该过程以退出代码1结束.

为什么这个Except块根本就被执行了?

NPE*_*NPE 6

sys.exit()加注SystemExit,这就是你所看到的.

至于它为什么不继承自Exception:

异常继承BaseException而不是StandardError或者 Exception因为它不会被捕获的代码意外捕获 Exception.这允许异常正确传播并导致解释器退出.