Playing around with errors in Python - KeyboardInterrupt

It's really hard to write code that doesn't throw errors, no matter what language one programs in. I've gotten used to writing modular code that helps maintain a constant train of thought and reduce the chance of errors occurring but still, from time to time, only after running the code do i go "Ohh, No!". I've been reading up on advanced concepts in python for about a week now and one thing I came across was the Python Standard Library reference of the Built-in Exceptions. I've come across most of these errors, a few more commonly than the rest. I thought that it'd be an interesting exercise to write code that intentionally raises the errors listed in that reference.

To start with, let's look at something that's not exactly an Error but is an interesting thing to play around with, KeyboardInterrupt. If a code is producing error messages or if it's not responsive or if you just wish to halt it, most of us press CTRL+C, which corresponds to KeyboardInterrupt. The interesting thing is that, the same way we can catch an exception using the try-except statements thereby preventing the program from halting, we can catch a KeyboardInterrupt and prevent it from halting out program. And just to rub it in, we can print annoying messages mocking the powerless user.

import time
from random import choice

ANNOYING_MSGS=["\n I'm sorry sir but I can't let you do that.",
                "\n You don't have power over me!!!",
                "\n I stop when I want to stop!!!"]

def main(i):
    print("running "+str(i)+" th loop")
    time.sleep(1)

for i in range(10):
    try:
        main(i)
    except KeyboardInterrupt:
        print(choice(ANNOYING_MSGS))

The Choice function from the random library is used to return one of the three annoying messages, which is then printed to the terminal when the user presses CTRL+C. That was one way of achieving what I set out to and I'm sure there are many more ways to prevent a Python process from stopping when a user tries to CTRL+C it. Well, that's all for now folks.

Popular posts from this blog

Animation using GNUPlot

Arxiv author affiliations using Python

Thoughts on the National Deep Tech Startup Policy