Python KeyboardInterrupt Exception
Example
Handle a KeyboardInterrupt:
try:
raise KeyboardInterrupt
except KeyboardInterrupt:
print("The program was stopped by the user")
Try it Yourself »
Definition and Usage
The KeyboardInterrupt exception occurs when the user stops a running program, usually by pressing Ctrl+C in the terminal.
The example raises it with raise, because you cannot press Ctrl+C in an online editor.
KeyboardInterrupt does not inherit from Exception, so except Exception does not catch it. This way, Ctrl+C still stops a program that catches other errors.
Related Pages
Read more about handling errors in our Python Try Except Tutorial.