The shape of the lesson
By the end of the lesson, learners can
- What is an exception?: Syntax errors stop a program being translated; logic errors give wrong answers.
- Writing exception-handling code: The 9618 pseudocode guide does not define any exception-handling statements, so you write this in your Paper 4 language.
- When to use exception handling: Exception handling is not a replacement for careful programming.
- Define: an exception is an unexpected event / error that occurs at run time and disrupts normal execution.
- Importance: no crash; meaningful message; files closed and data saved; the program can recover or retry.
- Code: risky statements in try; a handler for each expected exception; finally for tidying up.
- Appropriate when the cause is outside the program (files, devices, networks, conversions); use IF validation for predictable rules.
One picture every idea returns to
An exception is an unexpected event or error that happens while a program is running (a run-time error) and disrupts the normal flow of instructions, for example a file not found, division by zero, a failed type conversion or an array index out of range. If it is not handled, the program crashes. Exception handling places code that might fail in a try block; if an exception is raised (thrown), control jumps to a matching except / catch block, which can report the problem, retry or use a safe default, so the program can continue or end gracefully. An optional finally block runs either way, for tidying up such as closing files.
Forty-five minutes, phase by phase
| Time | Phase | What happens in the room | Grouping |
|---|---|---|---|
| 0 to 5 min | Hook: predict | Open with the question in the title, Expect the unexpected.. Files go missing, users type letters where numbers belong and networks drop out. Put the figure on the board: it is the one picture every idea in the lesson returns to. | Whole class, then pairs |
| 5 to 13 min | Teach and check: What is an exception? | Syntax errors stop a program being translated; logic errors give wrong answers. | Whole class, then pairs |
| 13 to 21 min | Teach and check: Writing exception-handling code | The 9618 pseudocode guide does not define any exception-handling statements, so you write this in your Paper 4 language. Model the worked example Trace the handler on the board, one line at a time. Your turn: In Python, a try block contains x = 10 / 0 and then print("A"). It has a handler except ZeroDivisionError: that prints B and a finally: block that prints C. After the whole structure, the program prints D. What is output? | Pairs |
| 21 to 30 min | Teach and check: When to use exception handling | Exception handling is not a replacement for careful programming. Model the worked example Choose and justify on the board, one line at a time. | Cooperative Concept Mapping |
| 30 to 36 min | Check | The four Stage 1 questions from the student lesson, answered on mini whiteboards or by show of fingers. Re-teach the one most get wrong. | Individual, then whole class |
| 36 to 43 min | Plenary | The exam-style questions from Stage 2, one at a time: thirty seconds alone, then a random call. The feedback lines in the key give the examiner's wording. | Individual, random call |
| 43 to 45 min | Exit and homework | Set the worksheet below (6 questions, 21 marks). Learners self-assess against the objectives before they leave. | Individual |
Protect the parts that carry the learning
The sequence carries about fifty minutes of material, so the lab is driven by one student while the class predicts rather than explored freely. Times are a guide.
Protected: the check at 30 minutes. It is the only individual read on whether the key idea landed, and it is not cut.
Cut first if the build overruns: the last check in When to use exception handling, never the check or the plenary.
In a 60 minute block: run worksheet questions 1 to 3 in class as a Rally Coach set and model both the hardest worked example and its check live.
Cooperative Concept Mapping
Teams receive the key terms on cards and arrange them on a large sheet, drawing and labelling the links. Compare maps between teams before showing the model map.
The full structure, with its variations and the other twelve, is on the cooperative-learning page.
What to head off, and how
| Trap learners fall into | Teaching move that pre-empts it |
|---|---|
| An exception is a run-time event. | Exception handling cannot catch a syntax error (the program would not run at all) and does not fix a logic error that simply produces the wrong answer. |
| Put only the statements that might fail, and the ones that depend on them, inside the try block. | Code after the failing statement in the try block is skipped, so a total updated after the risky conversion is safe, but one updated before it is not rolled back. |
| "Exception handling stops the program crashing" is only part of the answer. | To earn the marks, say what the handler does: outputs a meaningful message, retries, uses a default value, saves data or closes files. |
Exception handling: worksheet
6 questions, 21 marks. Written in the style of the papers; no past paper question is reproduced.
Explain what is meant by an exception and give two examples of situations that cause one.
Explain why exception handling is important in a program that saves customer orders to a file.
A Python program processes the list values = ["8", "0", "x", "4"]. For each item it runs, in a try block, n = int(item) followed by print(24 / n). The handlers are except ValueError: print("not a number") and except ZeroDivisionError: print("cannot divide"). State the output.
Write program code in a language of your choice that asks the user for the name of a file, opens it for reading and outputs every line. If the file cannot be found, the program must output a suitable message and ask for another file name until one can be opened.
State the purpose of a finally block and give an example of a statement that should be placed in one.
A student says: "I will put my whole program in one try block with one handler that catches every exception, so it can never crash." Evaluate this approach.
Answer key and marking notes
- An unexpected event / error that occurs while the program is running and disrupts the normal flow of execution.
- Example 1: trying to open a file that does not exist.
- Example 2: division by zero / converting non-numeric text to a number / array index out of range / loss of a network connection.
- Without it, a run-time error (e.g. disk full or file locked) would crash the program.
- The handler can give the user a meaningful message and let them retry or save elsewhere.
- Data already entered is not lost and the file can be closed safely, so it is not corrupted.
- "8": 24 / 8 = 3.0 is output.
- "0": int succeeds but 24 / 0 raises ZeroDivisionError: cannot divide.
- "x": int("x") raises ValueError: not a number.
- "4": 24 / 4 = 6.0 is output.
- A loop that repeats until a file has been opened successfully (e.g. a Boolean flag).
- Input of the file name inside the loop.
- The open statement inside a try block, setting the flag when it succeeds.
- An except / catch block for the file-not-found exception that outputs a meaningful message.
- After the loop, every line is read and output and the file is closed.
- It contains code that runs whether or not an exception was raised.
- Example: closing a file / releasing a resource / closing a network connection.
- It would stop the program crashing, but after any error the rest of the try block is skipped, so the program cannot carry on with its task.
- A single general handler cannot give a meaningful message or a suitable recovery for each different error.
- It can hide logic errors (bugs) that should be found and fixed, making testing harder.
- Better: put only risky statements in small try blocks with specific handlers, and use validation for predictable errors.
6 multiple-choice questions on this lesson
From the topic question bank. Assign them in the app for a marked score in your gradebook, or run the topic as a class game.
Which of these is an example of an exception?
- AA program tries to open a file for reading that has been deleted
- BA colon is missing at the end of an if statement, so the code will not run
- CA loop uses < instead of <= and the total is too small
- DA variable is given a name that does not describe its purpose
try:
n = int("7")
print("A")
r = 14 / (n - 7)
print("B")
except ValueError:
print("C")
except ZeroDivisionError:
print("D")
finally:
print("E")
print("F")What is output, in order?- AA, D, E, F
- BA, B, E, F
- CD, E, F
- DA, D, F
In which situation is an IF statement (validation) a better choice than exception handling?
- AChecking that an exam mark entered is from 0 to 100
- BReading data from a USB drive that may be removed
- CDownloading a file over a network connection that may drop
- DConverting text typed by the user into an integer
Why is exception handling important?
- AThe program can give a meaningful message, close files and continue instead of crashing
- BIt finds every syntax error before the program is run
- CIt guarantees that no run-time errors can ever occur
- DIt automatically corrects logic errors in the program
Scores.txt holds five lines: 10, 4.5, -3, seven and 9. The lesson's function is called:
def read_total(filename):
total = 0
try:
file = open(filename, "r")
except FileNotFoundError:
print("Cannot find", filename)
return -1
for line in file:
try:
total = total + int(line)
except ValueError:
print("Skipped a line that is not a whole number:", line.strip())
file.close()
return totalWhat happens when read_total("Scores.txt") runs?- ATwo lines are skipped with a message and 16 is returned
- BOne line is skipped with a message and 20.5 is returned
- COne line is skipped with a message and 10 is returned
- DTwo lines are skipped with a message and 22 is returned
total = 0
count = 0
for item in ["5", "x", "7"]:
try:
count = count + 1
total = total + int(item)
except ValueError:
print("bad")
print(total / count)What is output?- Abad, then 4.0
- Bbad, then 6.0
- C4.0 only
- Dbad, then the program crashes
Quiz key
A missing file is only discovered at run time, when the open fails, so it raises an exception. A missing colon is a syntax error found before the program runs, the wrong comparison is a logic error that gives a wrong answer without disrupting execution, and a poor variable name is a matter of style.
int("7") succeeds, so A is printed; then 14 / 0 raises ZeroDivisionError, so print("B") is skipped and the matching handler prints D. finally always runs (E) and the program continues (F). A, B, E, F misses the division by zero, D, E, F forgets that A printed before the error, and A, D, F leaves out the finally block.
A mark of 150 does not raise an exception; it is a predictable rule that a range check can test. A removed drive and a dropped connection are outside the program's control and can happen at any moment, and converting non-numeric text raises an exception that can be caught so the user is asked again.
A handler can report the problem in plain words, save data and close files safely, and let the program recover or retry. Syntax errors are found by the translator, run-time errors can still occur (handling deals with them rather than preventing them), and a logic error raises no exception for a handler to catch.
int("4.5") and int("seven") both raise ValueError, so two messages are printed and the loop continues; 10 + (-3) + 9 = 16. 20.5 assumes 4.5 converts, 10 assumes the first error ends the loop (the handler is inside the loop, so it carries on), and 22 treats -3 as 3.
For "x", count has already been increased to 2 before int("x") raises ValueError, and that change is not rolled back, so count ends at 3 and total at 12: bad is printed, then 12 / 3 = 4.0. 6.0 assumes the count was undone, 4.0 only forgets the handler's message, and nothing crashes because the ValueError is caught and count is not 0.
Slides for this lesson
A projectable deck for every pack is on the way. Until then, present the student lesson full screen: its sections, figure and lab tabs follow the same order as the plan above.