DMarlon Studio

Lesson 18 · 18 of 20

Errors with try and except · Python

Catch the errors in your Python program with try and except so it keeps going: bad numbers, division by zero and missing keys.

Python · Errors with try and except in DMarlon Studio: the example's code and its output in the terminal

When something goes wrong, Python raises an exception and, if nobody handles it, the program stops with an error message. try lets you have a go: if something in the block fails, Python jumps to the except instead of stopping.

In the first loop, int("seven") and int("3.5") raise a ValueError. The except ValueError: prints a warning and the loop moves on to the next text, so the total only adds 42 and 15.

A try can have several except blocks, one per kind of error. In slices_each(), dividing by 0 raises ZeroDivisionError, and dividing by a string raises TypeError. The else block only runs when there was no error: that is where the good result is printed.

except KeyError as error: stores the error itself in a variable so you can show it. Asking for the "juice" key, which is not in the dictionary, gives a message saying exactly which one is missing.

Code · main.py

# int() fails with text that is not a number: try catches it.answers = ["42", "seven", "3.5", "15"]total = 0for text in answers:    try:        number = int(text)        total += number        print(f"'{text}' -> {number}")    except ValueError:        print(f"'{text}' is not a whole number, skipped")print("Total:", total)# Different errors, different except blocks.def slices_each(pizzas, people):    try:        slices = pizzas * 8 // people    except ZeroDivisionError:        print("Nobody to share with!")    except TypeError:        print("People must be a number.")    else:  # runs only if there was no error        print(f"{people} people get {slices} slices each")slices_each(3, 4)slices_each(3, 0)slices_each(3, "four")# as gives you the error itself, with its message.prices = {"tea": 1.5, "coffee": 1.8}try:    print(prices["juice"])except KeyError as error:    print("No price for", error)

Output · python3 main.py

'42' -> 42
'seven' is not a whole number, skipped
'3.5' is not a whole number, skipped
'15' -> 15
Total: 57
4 people get 6 slices each
Nobody to share with!
People must be a number.
No price for 'juice'

Key points

  • Code that might fail goes inside try:.
  • except SomeError: handles only that kind of error.
  • else: runs when there was no error.
  • except ... as e: gives you the error and its message.
  • Catch specific errors, not everything at once.

Exercise

Write an ask_number() function that reads a number with input() and, if it is not valid, asks again inside a while loop until it is. Test it with an input.txt that has two wrong lines and a good one.