Handling errors and exceptions in Python

Handling errors and exceptions in Python

Understanding how to handle errors and exceptions with a simple program

This year, I made a promise to myself to try and understand every basic concept of this language called Python and the best way to go about it is to write a program every day.

If you transitioned from C programming to Python like me, you have probably run into several syntax errors already. A good example will be this:

while True
    x = int(input("What's x? "))
    print(f"x is {x}")

This simple code didn't run but I got an error message: " SyntaxError: expected ':' " since I am missing a ':' on line 1.

Errors are problems that stop our programs and a syntax error is a problem wrong with the code itself. It is a problem that you have to solve by following the syntax correctly.

while True:
    x = int(input("What's x? "))
    print(f"x is {x}")
    break

The fix here was just to include my missing ':' if I rerun that code, the user will be prompted for an integer and print said integer on the screen

. . . but there are still many things wrong with my code at this point.

There are other types of errors that happen while your code is running known as runtime errors. You might have to write additional codes to detect those errors because you don't know what input humans will type into your program so it is always best to be ready to deal with things they type or may mistype.

So for instance, I'm going to run my code again and type in "five" instead of 5

ValueError: invalid literal for int() with base 10: 'five'

$

Because I am currently using the int() to convert the user's input to a corresponding integer, python is not happy with me trying to pass 'five' to my program. What I can do here is rewrite my code to accommodate error handling. So, to catch a ValueError like in our program or some other types of errors except syntax errors, python has the try / except clause.

You can use try to check if something exceptional like a ValueError has occurred. Let's try it:

while True:
    try:
        x = int(input("What's x? "))
        print(f"x is {x}")
        break
    except ValueError:
        print("Your input must be an integer!")

Lines 3 and 4 of my code following try are the two lines of code that I am trying except if I see a value error which is when lines 7 will be executed

Running my code with an int 3 on my terminal:

$ python num.py

What's x? 3

x is 3

$

My code runs fine and breaks out of the while loop because I entered an integer, now let's see what happens when I type three instead

$ pythonnum.py

What's x? three

Your input must be an integer!

What's x? three

Your input must be an integer!

What's x? 4

x is 4

$

As you can see, when I tried typing three, my program detected the error and I was asked to try again until I typed 4 which is a corresponding integer and broke out of my loop.

As simple as my code is so far and even though it is correct, some programmers will argue that it is pythonic to only try the one or very few lines of code that can actually raise an exception. So since my previous versions had 3 lines of code including the break, feel free to play around with the code and improve it a little better by reducing it to just one line of code because that's exactly what I did

# Defines main function
def main():
    x = get_int()
    print(f"x is {x}")

# Defines get integer
def get_int():
    while True:
        try:
            num = int(input("x number? "))
        except ValueError:
            print("Your input must be an integer!")
        else:
            break
    return num

main()