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

Preview

Robust code

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

45 minutes

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?

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 plan B 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.

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.")

Name the exception

data-callouts.warning.label

Write except ValueError, not just except. A plain except hides every error, even your own bugs. Catch 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.

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

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

The lesson goes on

3 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.