Error handling

While testing your last challenge did you enter something that wasn’t an integer to see what would happen?

An error message from trying to force a string into an integer that wouldn't work

This happened because using the int function to force something into an integer only works if it can be an integer. “10” can become 10, but “Hello world” cannot become an integer. How to fix this?

Try…except

To get around this we can use the try…except keywords. They basically say “Try this code, but if you get an exception then do this instead”. So it will try the code indented under the try keyword and if everything goes well then it skips the except code. But if an error is raised then you can run the except block.

The except block can match different or multiple exception types. For now we’ll just use the ValueError as that is what the error message above showed we would get when trying to convert that string.

while True:
    try:
        input_number = int(input("Please enter a number: "))
        break
    except ValueError:
        print("That isn't a valid number")
print("Thank you for entering " + str(input_number))

Notice how in the print line we use str to convert the integer back to a string for concatenation.

This is only touching the surface of the try and except features. But it is enough for us to fix this problem.

For more information you can look at the documentation about it if you are having difficulty getting to sleep.

Mini challenge

Go back and alter your last challenge code to use try and except so that it can now handle a user typing in something that isn’t an integer.

Report a Glow concern
Cookie policy  Privacy policy

Glow Blogs uses cookies to enhance your experience on our service. By using this service or closing this message you consent to our use of those cookies. Please read our Cookie Policy.