Catching Errors

by Nigel George

Let’s say you have a simple function where you need to take the answer from a previous operation and divide it by 5:

ans = answer/5
print("Answer divided by 5 is", ans)

Seems straight forward, let’s try that out at the Python prompt:

So far, so good—but what if, instead of getting an integer, our function got handed a string? Let’s try that again in Python:

Oops! You will note that you didn’t even get to enter the final print() statement before Python threw an error. If this happened in the middle of an important part of your code, it could crash your program with potentially disastrous results.

Luckily, Python provides an easy, but robust way of handling errors within your code with the try ... except statement:

    # Try this piece of code 
    # On error, execute this bit of code.

Let’s try that now with our previous example:

In this case, all is OK and we get the expected output. Let’s try it again, but pass in a string this time:

This code is better, but we still have no idea what caused the error. Lucky for us, Python also captures the type of error.

If you look closely at the first bit of code that threw the error, you will see this line:

TypeError: unsupported operand type(s) for /: 'int' and 'str'

In this case, Python is telling us that the bad input is throwing a TypeError. So let’s modify the code to make it a bit more descriptive:

This is only a very basic example of error handling. It’s also incomplete (the code above will still crash if answer is zero); however, more complex implementations of the try...except statement build on these fundamentals. For more on the try...except statement, see errors and exceptions in the Python documentation. You can also find a comprehensive list of built-in exceptions in the Python docs.

Lesson Resources

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}