One bad cell stops the whole report
A report runs over 2000 rows. On row 1347 somebody typed "n/a" in an amount cell. The program stops with a wall of red text.
The owner sees nothing. She does not know which row, or what to do. Good error handling turns a crash into a clear message.
Key words
| Word | What it means |
|---|---|
| Float | a number with a decimal point, such as 12.5 |
| Exception | an error that stops code unless you handle it |
| Handle | catch an exception and decide what happens next |
| Try and except | code that tries something and, if it fails, runs a rescue instead |
| Dictionary | a collection of values, each found by a name called a key |
| Message | words shown to a user that say what went wrong and what to do |
| Fail safe | when something goes wrong, nothing is harmed and nothing is made up |
The cells students fill in are left blank in this preview.
By the end of this lesson
Note
I can catch common exceptions, give helpful messages and make a solution fail safely.
Starter
Have a go
Starter
3 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
This is practice
Important
The real task comes from the exam board. This lesson uses an invented organisation and its own made-up data. Your teacher tells you how the real tasks are set and what you may bring.
Run it: the crash
amounts = ["12.50", "n/a", "7"]
total = 0
for text in amounts:
total = total + float(text)
print(total)What the crash tells you
The program stopped on "n/a" with a ValueError. It never printed a total, and it never said which value was wrong.
Now wrap the risky line in try and except. The code carries on and tells the user the useful part.
Run it: the same data, handled
amounts = ["12.50", "n/a", "7"]
total = 0
skipped = []
for text in amounts:
try:
total = total + float(text)
except ValueError:
skipped.append(text)
print("Total", total)
print("Skipped", skipped)Worked example: common exceptions
| Exception | Cause | A helpful reaction |
|---|---|---|
| ValueError | Text that is not a number goes into float() | Say what was expected, with an example |
| ZeroDivisionError | Dividing by zero, such as an average of nothing | Say there is no data |
| KeyError | Asking a dictionary for a key it does not hold | Say the item is unknown, and name it |
| FileNotFoundError | A file is missing | Say which file, and where to put it |
The cells students fill in are left blank in this preview.