Python处理任何异常都会产生错误KeyboardInterrupt

时间:2018-07-29 11:23:00

标签: python exception

代码如下:

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 个答案:

答案 0 :(得分:1)

当您想抓住KeyboardInterrupt时,请明确:

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

答案 1 :(得分:0)

sudo apt-get install openjdk-8-jdk 不是Exception,而只是BaseException,因此您的KeyboardInterrupt没有处理它:

except

处理>>> issubclass(KeyboardInterrupt, Exception) False >>> issubclass(KeyboardInterrupt, BaseException) True 可让您访问任何异常,但不建议这样做:

BaseException