Skip to main content
 首页 » 编程设计

python之这个没有特色的 Python 异常是什么

2025年05月04日14lhb25

我在 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) 

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

如果删除 try/except block ,解释器不会显示错误。如果您捕获到特定错误,如 ValueError,则不会执行 except block 。

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) 

except block 未执行,进程结束并返回代码 0。那么,异常在层次结构中位于 Exception 之上?

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) 

产生

cow is the same as cow exception occurred, exiting with error.
Exception is: (0,)

进程以退出代码 1 结束。

为什么要执行这个 Except block ?

请您参考如下方法:

sys.exit()提高 SystemExit ,这就是您所看到的。

关于为什么不继承Exception:

The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit.