1

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 ?

1
  • 1
    You can use tuple of exceptions. except (Exception, KeyboardInterrupt): Commented Apr 22, 2022 at 11:48

2 Answers 2

4

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!

Sign up to request clarification or add additional context in comments.

Comments

4

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.