Python: 捕获异常或键盘中断

Python: catch Exception or keyboard interrupt

我有以下代码:

import time

try:
    time.sleep(3)
    raise Exception('error')
except Exception or KeyboardInterrupt:
    print(">>> Error or keyboard interrupt")

我想捕获错误或键盘中断。但目前只捕获Exception,不处理键盘中断

有没有办法同时捕获两者?

如果您想以不同的方式处理这两种情况,最好的方法是使用多个 except 块:

import time

try:
    time.sleep(3)
    raise Exception('error')

except KeyboardInterrupt:
    print("Keyboard interrupt")

except Exception as e:
    print("Exception encountered:", e)

注意顺序!

根据https://docs.python.org/3/tutorial/errors.html#handling-exceptions 你可以使用

except (RuntimeError, TypeError, NameError):
import time

try:
    time.sleep(3)
    raise Exception('error')
except (Exception, KeyboardInterrupt):
    print(">>> Error or keyboard interrupt")