【问题标题】:Can't catch SystemExit exception Python无法捕获 SystemExit 异常 Python
【发布时间】:2014-12-24 17:24:00
【问题描述】:

我正在尝试以下列方式捕获 SystemExit 异常:

try:
    raise SystemExit
except Exception as exception:
    print "success"

但是,它不起作用。

但是当我像这样更改我的代码时它确实有效:

try:
    raise SystemExit
except:
    print "success"

据我所知,except Exception as exception 应该会捕获任何异常。这也是here 的描述方式。为什么这里不适合我?

【问题讨论】:

    标签: python exception exception-handling


    【解决方案1】:

    作为documented,SystemExit 不继承自异常。你必须使用except BaseException

    但是,这是有原因的:

    异常继承自 BaseException 而不是 StandardError 或 Exception,因此它不会被捕获 Exception 的代码意外捕获。

    想要像处理 SystemExit 一样处理“真正的”异常是不寻常的。您最好使用except SystemExit 明确地捕获 SystemExit。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2010-09-15
    相关资源
    最近更新 更多