Python try / except

Sometimes your program needs to try something that may cause an error. Errors are also called exceptions.

For example, let’s say you ask your user for a number, but they don’t type a number:

# code
p = input("Tell me a price.")
taxed = p * 1.07
print("With tax that costs", taxed)

OUTPUT:
Tell me a price.>? turkey
    taxed = float(p) * 1.07
ValueError: could not convert string to float: 'turkey'

The part that failed was float(p). It is not possible to convert “turkey” to a floating point decimal number.

Sometimes the input values are out of your control. Here’s a way to tell Python what to do in case of an error:

p = input("Tell me a price.")
try:
    taxed = float(p) * 1.07
    print("With tax that costs", taxed)
except:
    print("You must enter a number.")

Does this remind you of if/else structures?

Under the try branch is the code that has the potential to throw an exception (error). Python will attempt that code, and if it does throw the exception, it instead runs the code under the except branch. The program then continues to run, unlike the previous example.

Try running that code. Type something dumb instead of a number, and you will find that the code does not crash anymore.

Specific Exceptions

Here’s a different version that allows Python to respond to different errors in different ways:

p = input("Tell me a price.")
try:
p = input("Tell me a price.")
try:
    qty = int(500 / float(p))
    print(f"For $500 you can buy {qty} of those")
except ValueError:
    print("You must enter a number.")
except ZeroDivisionError:
    print("Division by zero error.")
except:
    print("There was an error.")

Now the program knows how to deal with two specific types of exceptions: ValueError and ZeroDivisionError. If it’s a different type of error, the program runs that last branch, which doesn’t have a type of exception specified.

If you want a good time, check out theĀ Built-in Exceptions in Python.

If you want to add specific exceptions, just look at the error message you’re getting – the exception name is in the error message.