为什么"除了异常"没有捕获SystemExit?

Gar*_*Shi 11 python exception-handling

isinstance(SystemExit(1), Exception)evals to True,但这个片段打印出来"caught by bare except SystemExit(1,)".

try:
    sys.exit(0)
except Exception, e:
    print 'caught by except Exception', str(e)
except:
    print 'caught by bare except', repr(sys.exc_info()[1])
Run Code Online (Sandbox Code Playgroud)

我的测试环境是Python 2.6.

Rom*_*huk 13

isinstance(SystemExit(1), Exception) 在Python 2.6上是假的.自Python 2.4以来,此版本的Python中的异常层次结构已更改.

Eg KeyboardInterrupt不再是子类Exception.

查看更多信息http://docs.python.org/release/2.6.6/library/exceptions.html#exception-hierarchy

  • PEP 352提供了基本原理:http://www.python.org/dev/peps/pep-0352/#exception-hierarchy-changes (5认同)

Nou*_*him 11

SystemExit直接BaseException派生而不是从Exception派生.

Exception是父"所有内置的,非系统退出的异常"

SystemExit是"系统退出异常"(根据定义),因此不是派生自Exception.在您的示例中,如果您使用过BaseException,它将按照您原来的假设运行.


Sve*_*ach 8

您的错误出现在您问题的第一句话中:

>>> isinstance(SystemExit(1), Exception)
False
Run Code Online (Sandbox Code Playgroud)

SystemExit不是的子类Exception.

  • 谢谢,我发现真正的错误,在Python 2.3中,`isinstance(SystemExit(1),Exception)`是True.使用Python 2.3,测试代码打印出"被异常情况捕获".对于Python 2.6,这是正确的. (2认同)