gpt4 book ai didi

Python:为什么即使在退出后也会调用except

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

请检查下面的代码,

import sys
try:
seq=eval(raw_input("Enter seq number: "))
if seq <= 0 or seq >= 9999:
print "Sequence number not in range [0001-9999]"
sys.exit(1)
except:
print "!!! Sequence number not in range [0001-9999]"
sys.exit(1)

我给 eval raw_input 函数一个字符串。

$> python test.py
Enter seq number: "12"


Sequence number not in range [0001-9999]
!!! Sequence number not in range [0001-9999]

为什么在收到 exit 调用后还不退出?

最佳答案

sys.exit 只是引发一个异常 (SystemExit),然后被捕获。作为演示:

import sys
import traceback

try:
sys.exit(1)
except:
print "This threw the following exception:"
traceback.print_exc()
# This threw the following exception:
# Traceback (most recent call last):
# File "test.py", line 5, in <module>
# sys.exit(1)
# SystemExit: 1

关于Python:为什么即使在退出后也会调用except,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14568476/

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