gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:22 24 4
gpt4 key购买 nike

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

关于python - 这个没有特色的 Python 异常是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7477533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com