【问题标题】:What is this featureless Python exception?这个无特征的 Python 异常是什么?
【发布时间】:2011-09-19 21:29:35
【问题描述】:

我在 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 块,解释器不会显示错误。如果你捕捉到一个特定的错误,比如 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)

except 块没有被执行,进程以返回码 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 与发生cow 异常相同,错误退出。
例外是:(0,)

该过程以退出代码 1 结束。

为什么会执行这个 except 块?

【问题讨论】:

  • 在这种情况下打印 repr(k) 或 type(k) 比 k.args 提供更多信息。
  • 谢谢@Russell,这肯定会有所帮助。

标签: python exception python-2.6


【解决方案1】:

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

至于为什么它不继承自Exception

异常继承自 BaseException 而不是 StandardErrorException 这样它就不会被捕获的代码意外捕获 Exception。这允许异常正确地向上传播并导致解释器退出。

【讨论】:

    【解决方案2】:

    sys.exit() 简单地提高了SystemExit。这就是它退出程序的方式。当你捕获所有异常时,你也捕获了SystemExit

    【讨论】:

      【解决方案3】:

      除了其他答案:SystemExit不继承Exception,python异常层次结构:http://docs.python.org/library/exceptions.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-07
        • 1970-01-01
        • 2017-02-14
        • 1970-01-01
        相关资源
        最近更新 更多