Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.10 (1 of 2): Robust code

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

The cash machine and the wrong PIN

You type the wrong PIN at a cash machine. It does not crash. It does not show a strange code. It says: "Wrong PIN. You have 2 tries left."

The machine expected a mistake. Good programs expect mistakes too. Good code is robust: it keeps working when something unexpected happens.

Key words

WordWhat it meansExample
RobustKeeps working, or stops safely, when something unexpected happens.
ExceptionAn error that Python raises while the program runs.ValueError
tryStarts a block of code that might cause an exception.
exceptStarts the code that runs if the try block raises that exception.
Unexpected inputData the program did not plan for.letters in an age box
Error messageText that tells the user what went wrong and what to do.
ValidationA check that data is sensible.
CrashThe program stops because of an error it did not handle.

The cells students fill in are left blank in this preview.

Run it: a crash

Code: python
text = "twelve"
age = int(text)
print("Next year you will be", age + 1)

# Run it. Python raises an exception and the program stops.
# Read the last line of the message. What kind of exception is it?

Make a free account to save your work and track your progress.

Three signs of robust code

Robust code does three things.

  1. It copes with unexpected input. A letter in an age box does not crash it.
  2. It copes with unexpected endings. A missing file or a lost connection does not lose the user's work.
  3. It gives specific, meaningful error messages. The user learns what to do next.

Robust and not robust

SituationNot robustRobust
The user types "abc" for an ageThe program crashesIt says: please type a whole number
A data file is missingA long error appears and the program stopsIt says: budget.txt was not found. Check the name
The power fails while savingThe saved file is incompleteThe program saves often, so little is lost
The user divides by zeroThe program stopsIt says: you cannot divide by zero

The cells students fill in are left blank in this preview.

Catching an exception

Python has a tool for this. Put the risky code in a try block. Put the backup plan in an except block.

If nothing goes wrong, Python skips the except block. If an exception happens, Python jumps to it.

Try it: try and except

Code: python
text = "twelve"

try:
    age = int(text)
    print("Next year you will be", age + 1)
except ValueError:
    print("Please type your age as digits, for example 12.")

# Change "twelve" to "12" and run it again.

Make a free account to save your work and track your progress.

Try it: two more exceptions

Code: python
try:
    print(10 / 0)
except ZeroDivisionError:
    print("You cannot divide by zero.")

try:
    file = open("budget_2026.txt")
    print(file.readline())
    file.close()
except FileNotFoundError:
    print("budget_2026.txt was not found. Check the file name.")

Make a free account to save your work and track your progress.

Name the exception

Warning

Many people think a plain except is safest because it catches everything. It also hides your own bugs. Write except ValueError, naming the exception you expect, and let the rest show.

A good error message

Bad messageWhy it is badBetter message
Error 7The user cannot tell what it meansYour age must be a whole number, such as 16.
Invalid inputIt does not say which input or whyThe postcode must have 5 to 8 characters.
Something went wrongNo clue what to do nextThe file could not be saved. Check you have space, then try again.

The cells students fill in are left blank in this preview.

Match the problem to a good message

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Quick check: robust or not?

Have a go

Quick check: robust or not?

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Watch: robust code

Press Play on the short film below. It runs the programs from this lesson, one at a time. Watch where Python jumps when something goes wrong, and why naming the exception matters.

Film: robust code

Robust code

Every scene, as text

  1. Not robust: a crash. text is set to "twelve", and int(text) cannot change letters into a whole number, so Python raises an exception, a ValueError, and the program stops. The last line of Python's message is ValueError: invalid literal for int() with base 10: 'twelve'. The print line never runs (struck through).
  2. The cure is try and except: the risky code goes in a try block, the backup plan in an except block. int(text) raises the same ValueError, so Python jumps to except ValueError, skipping the print after it (struck through), and the program prints Please type your age as digits, for example 12. The message tells the user what to do next.
  3. Change "twelve" to "12", as the lesson asks. int(text) gives 12 and nothing goes wrong, so the try block runs to its end and prints Next year you will be 13. With no exception, Python skips the except block (struck through).
  4. The same tool copes with other unexpected problems. 10 / 0 raises a ZeroDivisionError, so nothing is printed from the try block. except ZeroDivisionError names that exception, so its block runs and prints You cannot divide by zero. A specific, meaningful message, and no crash.
  5. Myth (false): a plain except is safest because it catches everything. Here text is "12", a good age, but int(txt) has a typo, txt for text, so Python raises a NameError and the print after it never runs (struck through). The plain except catches that too and prints Please type your age as digits, for example 12. The message tells the user to fix an age that was fine, and the bug stays hidden.
  6. The cure: name the exception you expect, and let the rest show. except ValueError catches a ValueError only, so the NameError is not caught: neither print runs (both struck through) and the program stops. The last line of Python's message is NameError: name 'txt' is not defined. Did you mean: 'text'? The bug shows, so it can be found and fixed.

Your turn: make it robust

Make four functions robust. Use try and except.

  1. safe_int(text) gives back a whole number, or None if the text is not one.
  2. safe_divide(a, b) gives back the answer, or the text "Cannot divide by zero".
  3. read_first_line(filename) gives back the first line of a file, or "File not found: " and the file name.
  4. average_of_text(values) ignores anything that is not a whole number and gives back the average of the rest. Tip: use your safe_int.

Press Run Tests to check.

Code: python
def safe_int(text):
    # Change the text into a whole number. If it cannot be changed, give back None.
    # "12" gives 12. "abc" and "3.5" and "" give None. Use try and except.
    return "not done"


def safe_divide(a, b):
    # Give back a divided by b. If b is 0, give back the text "Cannot divide by zero".
    # Use try and except ZeroDivisionError.
    return "not done"


def read_first_line(filename):
    # Give back the first line of the file, without the line break.
    # If the file does not exist, give back "File not found: " and then the filename.
    return "not done"


def average_of_text(values):
    # values is a list of text, such as ["10", "x", "20"].
    # Ignore any text that is not a whole number. Give back the average of the rest.
    # If there are none, give back 0.
    return "not done"

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.