Python处理任何异常都出现错误,如何解决 KeyboardInterrupt?

3
这里是代码:
try:
    input() # I hit Ctrl+C
except Exception as e:
    print(str(e))

以下是跟踪信息:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\test.py", line 2, in <module>
    input()
KeyboardInterrupt
2个回答

2

当您想捕获 KeyboardInterrupt 时,请明确说明:

try:
    input() # I hit Ctrl+C
except Exception as e:
    print(str(e))
except KeyboardInterrupt :
    print 'ok, ok, terminating now...'

那么如果我想处理任何异常的文本,但我不知道每个异常的名称,我该怎么做? - Joe Doe
@JoeDoe 看一下上面的代码,except KeyboardInterrupt 捕获 Ctrl/C,你可以在下一个 except 语句中处理所有其他异常。或者你想要完全不同的做法吗? - lenik
@JoeDoe,你不需要这样做,因为这不是显式的(你将处理哪些异常?你期望你的代码会引发什么?等等)。显式优于隐式。然而,一般来说,如果你捕获了BaseException,那么所有其他的异常也应该被捕获。 - Nelewout
我希望代码能够处理任何异常。因为我不知道 KeyboardInterrupt,只处理了 Exception,然后出现了错误。所以我想处理任何异常 as eprint(str(e)) - Joe Doe
@JoeDoe捕获每个异常并不是一个好主意,因为你不能使用Ctrl/C中断你的程序。 - lenik
谢谢。我会记住的。 - Joe Doe

0

KeyboardInterrupt 不是一个异常,而只是一个基本异常,因此你的except无法处理它:

>>> issubclass(KeyboardInterrupt, Exception)
False
>>> issubclass(KeyboardInterrupt, BaseException)
True

处理BaseException可以访问任何异常,但不建议使用:

try:
    # ...
except BaseException as e:
    print(str(e))

那么,如果我想处理任何异常的文本,但我不知道每个异常的名称,我该怎么做? - Joe Doe
你可以使用except BaseException:或者直接使用except:,但两者都被不鼓励使用,因为在你的示例中等其他情况下,这会导致程序无法中断。最好尽可能明确,并在需要处理更多异常类型时添加它们。 - user2390182
如果在except中无法获取异常文本,我将尝试使用BaseException,谢谢。 - Joe Doe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接