I have the following code:
import time
try:
time.sleep(3)
raise Exception('error')
except Exception or KeyboardInterrupt:
print(">>> Error or keyboard interrupt")
I want to catch either error or key board interrupt. But currently, it catches only Exception, keyboard interrupt is not handled.
- If I remove Exception and leave only Keyboard interrupt, it catches only keyboard interrupt.
- If I remove KeyboardInterrupt and leave only Exception, it catches only Exception.
Is there a way to catch both ?
CodePudding user response:
If you want to handle the two cases differently the best way of doing this is to have multiple except
blocks:
import time
try:
time.sleep(3)
raise Exception('error')
except KeyboardInterrupt:
print("Keyboard interrupt")
except Exception as e:
print("Exception encountered:", e)
Mind the order!
CodePudding user response:
According to https://docs.python.org/3/tutorial/errors.html#handling-exceptions you can use
except (RuntimeError, TypeError, NameError):
import time
try:
time.sleep(3)
raise Exception('error')
except (Exception, KeyboardInterrupt):
print(">>> Error or keyboard interrupt")