Python Foundations

Exception Handling

Catching and handling run-time errors so a program does not crash — try/except structure, ZeroDivisionError, FileNotFoundError, ValueError, validating user input, and handling multiple exception types at once.

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.

Definition:
  • 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.
Exception vs syntax error:
  • 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.
SituationCause type
User types "hello" instead of a numberUser error
Division by zeroProgramming error (run-time)
Hard disk fails while writingHardware failure
Missing colon after if statementSyntax error (NOT 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.
Exam tip:
  • 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.

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
ENDTRY

Python

try:
    # statements that might cause an error
except:
    # statements to handle the error
    print("Something went wrong")
Key rule:
  • The try block runs first.
  • If any line inside it raises an exception, Python immediately jumps to the matching except block and runs that instead.
  • If no exception happens, the except block is skipped completely.

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.

Your Turn — ShowAverage — division by zero [4 marks]
Write program code that asks for a total of marks and a number of students, outputs the average, and uses exception handling to deal with a division by zero.
Hint:
  • 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
Your Turn — PerItem — discount per item
Write a function PerItem() that asks for a total discount and number of items, outputs the discount per item, and handles division by zero.
Hint:
  • Read TotalDiscount and Items as integers
  • Divide inside try
  • Catch ZeroDivisionError with a message
Your Turn — Integer division
Two integers a and b are stored. Print a // b, or "div by zero" if b is 0.
Hint:
  • Only the print(a // b) line is risky
  • Wrap it in try
  • Catch ZeroDivisionError
Your Turn
A float price and an integer people are stored. Print the share each person pays, or "no people" if people is 0.
Hint:
  • Same shape — just change the names and the message
  • price / people inside try
  • Catch ZeroDivisionError
Exam tip:
  • 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 plain except.
  • What you must never skip is the print of a sensible message inside it.

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.

Your Turn — ReadScores — file not found [5 marks]
Write program code for a procedure ReadScores() that opens the text file scores.txt, prints each line, and uses exception handling to output a message if the file cannot be opened.
Hint:
  • Open inside try
  • Loop and print each stripped line
  • Close after the loop
  • Single except with the message
Your Turn — ReadNames — file exception
Write a procedure ReadNames() that opens names.txt, prints each line, and prints "Cannot open file" if the file cannot be opened.
Hint:
  • Same structure as ReadScores
  • Change filename and message
  • Open inside try, loop, close, except
Your Turn — Read whole file
Open log.txt, print its whole contents, and print "no log" if it cannot be opened.
Hint:
  • Open inside try, print f.read(), close
  • Except: print "no log"
Your Turn
Open config.txt, print its whole contents, and print "no config" if it cannot be opened.
Hint:
  • Identical structure, change the filename and message
Exam tip:
  • 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 open line before the safety net starts.
  • You then lose the exception-handling mark.

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.

Your Turn — ReadNumber — validate integer input [4 marks]
Write program code that asks the user for a whole number and prints it. If the user types something that is not a whole number, output a clear message using exception handling.
Hint:
  • Read raw string with input()
  • Convert with int() inside try
  • Catch ValueError
  • Print a clear error message
Your Turn — ReadPrice — validate float input
Write a function ReadPrice() that asks for a price (decimal). If the user types something invalid, print "Invalid price" using exception handling.
Hint:
  • Use float() for a decimal
  • Catch ValueError
  • Read raw input first, convert inside try

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.

Your Turn — Process — three exceptions at once [6 marks]
Write program code that opens a file nums.txt, reads two integers from the user, divides the first by the second, and handles a missing file, an invalid number, and division by zero — each with its own message.
Hint:
  • One try, three except blocks
  • Order: file → value → zero
  • FileNotFoundError, ValueError, ZeroDivisionError
  • Each except prints a different message
Your Turn — Scale — three exceptions
Write a function Scale() that opens settings.txt, reads two integers (Amount, Divisor), prints Amount // Divisor, and handles missing file, invalid number, and division by zero.
Hint:
  • Same structure as Process
  • Change filenames and variable names
  • Three except blocks in order

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.

(a) — Define an exception [2 marks] State what is meant by an exception and give one example of a cause.
Your Turn — (a) Model answer
State what is meant by an exception and give one example of a cause. [2 marks]
Hint:
  • 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
(b) — LoadBooks() [6 marks] Write program code for 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.
Your Turn — (b) Model answer
Write program code for LoadBooks() that opens books.txt, reads each line into global BookList, and handles a missing file. [6 marks]
Hint:
  • Use global BookList
  • Open inside try
  • Loop, strip, append each line
  • Close the file
  • Except: print "Library file missing"
(c) — AveragePerShelf() [4 marks]
  • 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.
Your Turn — (c) Model answer
Write AveragePerShelf() that reads total books and shelves, returns the average, and handles division by zero. [4 marks]
Hint:
  • Read Total and Shelves as integers
  • Divide inside try
  • Catch ZeroDivisionError: print "No shelves", return 0
  • Return the average if successful

Key Points Summary

An exception is a run-time event that disrupts normal flow — not a syntax error (compile-time).
Three causes: hardware failure, programming error (run-time), user error.
Exception handling prevents crashes, improves UX, and handles unpredictable problems.
Python: try/except. Pseudocode: TRY...EXCEPT...ENDTRY.
try runs first; if an exception occurs, Python jumps to the matching except block.
If no exception, the except block is skipped completely.
ZeroDivisionError — catch with except ZeroDivisionError: (or bare except:).
FileNotFoundError — put open() INSIDE try, not before it.
ValueError — catch when int() or float() fails on bad user input.
Read raw input first, then convert inside try — never convert before try.
Multiple except blocks: Python runs the FIRST one whose type matches.
Always print a sensible message inside except — an empty except earns no marks.
A bare except: (no type) is accepted in Paper 4; naming the error is good practice.

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.

Exam tip:
  • 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.
1Practice Task — Basic try/except [2 marks]
Write a try/except block that prints "OK" if x = 10 succeeds, or "Error" if it fails.
2Practice Task — Division by zero [3 marks]
Two integers a and b are stored. Print a / b, or "Error: divide by zero" if b is 0.
3Practice Task — Average with exception [4 marks]
Write a function ShowAverage() that reads a total and count, prints total/count, and handles division by zero.
4Practice Task — File not found [4 marks]
Write a procedure ReadFile() that opens data.txt, prints each line, and prints "File not found" if it cannot be opened.
5Practice Task — Read whole file [3 marks]
Open log.txt, print its whole contents, and print "no log" if it cannot be opened.
6Practice Task — Validate integer input [4 marks]
Write a function ReadNumber() that asks for a whole number, prints it, and prints "Invalid" if the user does not enter a number.
7Practice Task — Validate float input [4 marks]
Write a function ReadPrice() that asks for a price (float), prints it, and prints "Invalid price" on bad input.
8Practice Task — Multiple exceptions [6 marks]
Write a function Process() that opens nums.txt, reads two integers, divides them, and handles missing file, invalid number, and division by zero — each with its own message.
9Practice Task — Load list from file [5 marks]
Write a function LoadNames() that opens names.txt, appends each stripped line to a global list NameList, and prints "File missing" on error.
10Practice Task — Average with return + exception [4 marks]
Write a function AveragePerShelf() that reads total books and shelves, returns total/shelves, and returns 0 with "No shelves" message if shelves is 0.
11Practice Task — Define an exception [2 marks]
State what is meant by an exception and give one example of a cause.
12Practice Task — Exception vs syntax error [2 marks]
Explain the difference between an exception and a syntax error.
13Practice Task — Three causes of exceptions [3 marks]
State the three categories of causes of exceptions.
14Practice Task — Why open() inside try [2 marks]
Explain why the open() call should be placed inside the try block, not before it.
15Practice Task — Bare except vs named [2 marks]
Explain the difference between except: and except ZeroDivisionError:. Which is preferred and why?

Question Bank

Answer all questions, then press Submit Quiz to see your score.

0/12 answered

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.