11.1 What is an Exception?
You have already written programs that ask the user for a number, open a file, or do a calculation. Most of the time they work. But what happens when the user types "hello" instead of a number? Or asks to open a file that does not exist? Up to now, your program probably just stopped and printed a long red error message. That is called crashing.
- An exception is an event that happens while a program is running that disrupts the normal flow of instructions.
- Left alone, it makes the program halt (stop) before it has finished.
- An exception is not a typing mistake that stops code compiling — that is a syntax error, caught before the program runs.
- An exception happens during execution, often because of something outside your control: what the user types, whether a file exists, what is on the disk.
| Situation | Cause type |
|---|---|
| User types "hello" instead of a number | User error |
| Division by zero | Programming error (run-time) |
| Hard disk fails while writing | Hardware failure |
| Missing colon after if statement | Syntax error (NOT an exception) |
What is an Exception?
11.2 Why & When to Use Exception Handling
Exception handling earns its place for three reasons:
- It prevents crashes. The program keeps working even when something unexpected happens, so the user is never thrown out to an error screen.
- It improves the user experience. Instead of a confusing red traceback, the user sees a short, clear message like "File not found" and can try again.
- It handles problems you cannot prevent in advance. You cannot guarantee a file exists, or that the user will type sensibly, or that the disk will not fail. Exception handling is your safety net for exactly these cases.
- Use exception handling for risky operations: file I/O, user input conversion, division.
- Do not wrap every line — only the lines that might actually fail at run-time.
Why & When to Use Exception Handling
11.3 The try/except Structure
In Cambridge pseudocode, exception handling is written as a TRY ... EXCEPT ... ENDTRY block. The risky code goes in the TRY part; the recovery code goes in the EXCEPT part.
Cambridge pseudocode
TRY
// statements that might cause an error
EXCEPT
// statements to handle the error
ENDTRYPython
try:
# statements that might cause an error
except:
# statements to handle the error
print("Something went wrong")- The
tryblock runs first. - If any line inside it raises an exception, Python immediately jumps to the matching
exceptblock and runs that instead. - If no exception happens, the
exceptblock is skipped completely.
The try/except Structure
11.4 Handling Division by Zero
Imagine a program that works out an average mark by dividing the total by the number of students. If the number of students is zero, the division crashes. We wrap the risky division in try and catch the specific error in except ZeroDivisionError.
- Only the division line is risky — put it inside try
- Catch ZeroDivisionError
- Print the average if successful
- Print an error message if division by zero
- Read TotalDiscount and Items as integers
- Divide inside try
- Catch ZeroDivisionError with a message
- Only the print(a // b) line is risky
- Wrap it in try
- Catch ZeroDivisionError
- Same shape — just change the names and the message
- price / people inside try
- Catch ZeroDivisionError
- Naming the exact exception (
except ZeroDivisionError:) is good practice. - A bare
except:with the right message also gains the mark in Paper 4 — the official model answers often use a plainexcept. - What you must never skip is the print of a sensible message inside it.
Division by Zero & File Exceptions
11.5 File Handling Exceptions
Opening a file that does not exist raises FileNotFoundError. Wrap the open() call inside try so the program prints a friendly message instead of crashing.
- Open inside try
- Loop and print each stripped line
- Close after the loop
- Single except with the message
- Same structure as ReadScores
- Change filename and message
- Open inside try, loop, close, except
- Open inside try, print f.read(), close
- Except: print "no log"
- Identical structure, change the filename and message
- Put the
open()call inside the try block, not before it. - If you open the file first and only wrap the loop, a missing file crashes on the
openline before the safety net starts. - You then lose the exception-handling mark.
Division by Zero & File Exceptions
11.6 Validating User Input
When the user types something that cannot be converted to a number, int() or float() raises ValueError. Read the raw input first, then convert inside try.
- Read raw string with input()
- Convert with int() inside try
- Catch ValueError
- Print a clear error message
- Use float() for a decimal
- Catch ValueError
- Read raw input first, convert inside try
Validating User Input
11.7 Handling Several Errors at Once
You write the risky code once inside try, then list each error type in its own except block. Python runs the first except whose type matches the exception that was raised.
- One try, three except blocks
- Order: file → value → zero
- FileNotFoundError, ValueError, ZeroDivisionError
- Each except prints a different message
- Same structure as Process
- Change filenames and variable names
- Three except blocks in order
Multiple Exceptions & Key Points
11.8 Full Exam-Style Question
The text file books.txt stores one book title on each line. The program uses a global list BookList.
- An exception is an event during execution that disrupts normal flow
- It makes the program halt before finishing
- Example: division by zero, missing file, invalid input
LoadBooks() that opens books.txt, reads each line into the global list BookList, and uses exception handling to print "Library file missing" if the file cannot be opened.- Use global BookList
- Open inside try
- Loop, strip, append each line
- Close the file
- Except: print "Library file missing"
- Write program code for
AveragePerShelf()that reads the total number of books and the number of shelves from the user, and returns the average books per shelf. - It must output "No shelves" and return 0 if the number of shelves is zero.
- Read Total and Shelves as integers
- Divide inside try
- Catch ZeroDivisionError: print "No shelves", return 0
- Return the average if successful
✓ Key Points Summary
11.9 Practice Tasks
Fifteen exam-style exception handling tasks. Each shows only the question — click Hint for the thought process, or Help for the worked solution.
- For every exception handling task, the marker checks: (1) correct try/except structure, (2) risky code inside try, (3) a sensible message inside except, (4) the correct exception type (or bare except).
- The most common mark loss is forgetting to print a message in the except block.
Question Bank
Answer all questions, then press Submit Quiz to see your score.
Question 1Multiple Choice
What is an exception?
Question 2True / False
A missing colon after an if statement is an exception.
Question 3Multiple Choice
Which Python keywords handle exceptions?
Question 4Multiple Choice
Which exception does division by zero raise?
Question 5True / False
If no exception occurs in try, the except block is skipped.
Question 6Multiple Choice
Which exception does int("hello") raise?
Question 7Multiple Choice
Where should open() be placed when handling file exceptions?
Question 8True / False
A bare except: (no error type) is accepted in Paper 4 mark schemes.
Question 9Multiple Choice
How do you handle multiple exception types?
Question 10Multiple Choice
Which exception does opening a non-existent file raise?
Question 11True / False
The except block must always print a sensible message in Paper 4.
Question 12Multiple Choice
Which is the correct pattern for validating integer input?
Answer all 12 questions to enable submission.