gpt4 book ai didi

python - KeyboardInterrupt 不会在广泛异常的情况下引发或捕获

转载 作者:行者123 更新时间:2023-11-28 22:49:21 25 4
gpt4 key购买 nike

有人可以向我解释以下内容吗?让我们看一下代码:

if __name__ == '__main__':
try:
while 1:
x = 2+2
except KeyboardInterrupt:
print('yo')

如果我运行这个,等一会儿,然后按Ctrl+C,一个异常将被处理并且消息yo将打印出来。

如果我们更改代码以捕获像这样的广泛异常:

if __name__ == '__main__':
try:
while 1:
x = 2+2
except Exception, e:
print('yo')
print(e)

运行它,稍等片刻,按Ctrl+C,不会捕获到KeyboardInterrupt异常。

根据 Python documentation :

Python installs a small number of signal handlers by default: SIGPIPE is ignored (so write errors on pipes and sockets can be reported as ordinary Python exceptions) and SIGINT is translated into a KeyboardInterrupt exception. All of these can be overridden.

那么,为什么在第二种情况下没有捕获甚至引发此异常?

最佳答案

您不能通过捕获 Exception 来捕获 KeyboardInterrupt因为前者继承自 BaseException仅有的。您可以在 docs 中阅读相关信息:

exception KeyboardInterrupt

Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. Interrupts typed when a built-in function input() or raw_input() is waiting for input also raise this exception. The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting. (Emphasis mine)

这意味着您必须:

except BaseException, e:

但这被认为是一种不好的做法。最好像您的第一个示例一样捕获 KeyboardInterrupt 本身。

关于python - KeyboardInterrupt 不会在广泛异常的情况下引发或捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23915740/

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