AQA A-Level Computer Science
Programming Tasks: Exception Handling and File Handling
Total marks: 50
These tasks are written in the style of AQA Paper 1 (on-screen practical). Programs may be written
in Python, [Link], C#, Java, Pascal/Delphi or Haskell. Mark scheme answers use Python.
01 Write a program that asks the user to enter their age in years.
The program should:
• Use exception handling to deal with input that is not a valid whole number
• If the user enters something that is not a whole number, display the
message Please enter a whole number and ask them again
• Continue asking until a valid whole number is entered
• Once a valid age has been entered, display the message You are X years
old, where X is the value entered
Example
If the user enters twenty, then 12.5, then 21, the program should display:
Please enter a whole number
Please enter a whole number
You are 21 years old
Evidence that you need to provide
Include the following evidence in your Electronic Answer Document.
01.1 Your PROGRAM SOURCE CODE.
[8 marks]
01.2 SCREEN CAPTURE(S) showing the result of testing the program by entering:
• abc
• 12.5
• 21
[1 mark]
02 Create a folder/directory called Question02 for your new program.
A text file called [Link] already exists in this folder. The file contains the
names of students, with one name per line, as shown in Figure 1.
Figure 1
Alice
Bob
Charlie
Diana
Ethan
Task 1
Write a program that opens the file [Link], reads each name from the file,
and displays each name on a new line in the format 1. Alice, 2. Bob, and so on.
The program should close the file after reading.
Task 2
Improve the program so that it uses exception handling. If the file [Link]
cannot be found, the program should display the message File not found
instead of crashing.
Task 3
Test the program works correctly:
• with the file [Link] present in the folder
• with the file [Link] removed (or renamed) so it cannot be found
Save the program in your Question02 folder/directory.
Evidence that you need to provide
Include the following evidence in your Electronic Answer Document.
02.1 Your PROGRAM SOURCE CODE.
[10 marks]
02.2 SCREEN CAPTURE(S) showing the program running successfully:
• with the file present
• with the file missing
[1 mark]
03 Create a folder/directory called Question03 for your new program.
Write a program that allows the user to build a shopping list and save it to a text
file.
The program should:
• Repeatedly ask the user to enter a shopping item
• Stop asking for items when the user enters STOP (the program should
accept STOP in any case, e.g. stop, Stop, STOP)
• Append every item entered (other than the stop word itself) to a text file
called [Link]
• Use exception handling so that, if the file cannot be opened for writing, the
program displays Unable to save list and ends without crashing
• After the user has finished, display the message X items added to
[Link], where X is the number of items added
Example
If the user enters bread, milk, eggs, STOP, the program should display:
3 items added to [Link]
…and the file [Link] should contain the three items, one per line.
Evidence that you need to provide
Include the following evidence in your Electronic Answer Document.
03.1 Your PROGRAM SOURCE CODE.
[10 marks]
03.2 SCREEN CAPTURE(S) showing the program running with the inputs:
• bread
• milk
• eggs
• STOP
• the contents of [Link] after running
[1 mark]
04 Create a folder/directory called Question04 for your new program.
A text file called [Link] contains numerical values, with one value per line.
Some lines may contain values that are not valid whole numbers. The example file
shown in Figure 2 contains seven lines.
Figure 2
12
45
abc
78
23.5
99
Write a program that:
• Opens the file [Link] for reading
• Reads each line of the file
• For each line that contains a valid integer, includes that integer in the
calculations
• For each line that does not contain a valid integer, displays the message
Skipped: <line> (where <line> is the content of the line) and continues
processing
After reading all lines, the program should display:
• The maximum integer found
• The minimum integer found
• The average (mean) of the valid integers, to 2 decimal places
The program should use exception handling for the following situations:
• If the file [Link] cannot be found, display File [Link] not
found and end the program without crashing
• Lines that cannot be converted to an integer are handled as described
above
You may assume that the file contains at least one valid integer.
Save the program in your Question04 folder/directory.
Evidence that you need to provide
Include the following evidence in your Electronic Answer Document.
04.1 Your PROGRAM SOURCE CODE.
[14 marks]
04.2 SCREEN CAPTURE(S) showing the program running with the contents of
[Link] as in Figure 2.
[1 mark]
Mark Scheme
Programming Tasks: Exception Handling and File Handling
AO2 = Apply knowledge and understanding to a given context.
AO3 = Design, program and evaluate computer systems.
Mark holistically. Do not deduct marks for minor syntax issues that do not affect program logic.
Accept equivalent constructs in any approved language.
Question 01 — Validating numeric input [9 marks]
01.1 Source code [8 marks — AO2 (2), AO3 (6)]
Award 1 mark for each of the following points, MAX 8:
• Loop / iterative structure used to repeatedly request input
• Uses input() to ask the user for their age
• Conversion of input to an integer using int() (or equivalent)
• Conversion is wrapped in a try block
• Catches ValueError (or equivalent) in an except clause
• Displays the exact message Please enter a whole number inside the except clause
• Loop terminates correctly once a valid whole number is entered
• Final output displays You are X years old where X is the entered value
Example fully-correct answer:
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("Please enter a whole number")
print("You are", age, "years old")
A. while loop, do-while equivalent, or recursion.
R. catching a generic Exception — accept the catch mark only if no other except clause is present.
01.2 Screen captures [1 mark]
• Screen capture clearly shows all three inputs (abc, 12.5, 21) and the resulting outputs in the
correct order.
Question 02 — Reading from a file with exception handling [11 marks]
02.1 Source code [10 marks — AO2 (3), AO3 (7)]
Task 1 — basic file reading (5 marks):
• Opens [Link] in read mode (e.g. "r")
• Iterates through every line / reads all lines from the file
• Maintains a counter (or uses enumerate) to number entries starting from 1
• Displays each entry in the format 1. Alice, 2. Bob etc. (number, dot, space, name)
• Closes the file after reading (or uses with-open construct)
Task 2 — exception handling (5 marks):
• Wraps the file opening (and reading code) inside a try block
• Catches FileNotFoundError (A. IOError, OSError)
• Displays the exact message File not found when the exception is caught
• Program ends gracefully — does not crash or display a stack trace when file is missing
• Original Task 1 functionality is preserved when the file is present
Example fully-correct answer:
try:
file = open("[Link]", "r")
count = 1
for line in file:
name = [Link]()
print(str(count) + ". " + name)
count = count + 1
[Link]()
except FileNotFoundError:
print("File not found")
A. trailing newline characters left in output (e.g. 1. Alice\n) — accept the format mark provided
the number-dot-space prefix is correct.
R. answer that hard-codes the names rather than reading them from the file — score 0 for Task 1.
02.2 Screen captures [1 mark]
• Two screen captures showing both test cases: one with the file present (numbered list of
names displayed), and one with the file missing ("File not found" displayed).
Question 03 — Writing to a file with exception handling [11 marks]
03.1 Source code [10 marks — AO2 (3), AO3 (7)]
• Initialises a counter for items added (1)
• Loop repeatedly asks the user for an item (1)
• Loop exits when the user enters STOP (1)
• STOP comparison is case-insensitive (e.g. uses .upper() or .lower()) (1)
• Opens [Link] in append mode "a" (A. "w" only if file is opened once outside the
loop) (1)
• Writes each entered item to the file, each on its own line (1)
• File operations are wrapped in a try block (1)
• Catches IOError / OSError (A. PermissionError, or Exception if no other catch present)
(1)
• Displays the exact message Unable to save list on error (1)
• Final message displays X items added to [Link] with X being the correct count
(1)
Example fully-correct answer:
count = 0
try:
file = open("[Link]", "a")
while True:
item = input("Enter an item (or STOP to finish): ")
if [Link]() == "STOP":
break
[Link](item + "\n")
count = count + 1
[Link]()
print(str(count) + " items added to [Link]")
except IOError:
print("Unable to save list")
A. opening the file inside the loop (less efficient but functionally equivalent — provided it appends,
not overwrites).
R. opening in "w" mode inside the loop — overwrites previous items each iteration. Score 0 for the
file-write mark.
03.2 Screen captures [1 mark]
• Screen capture shows the four inputs (bread, milk, eggs, STOP), the final count message,
and the contents of [Link] after running.
Question 04 — Combined task [15 marks]
04.1 Source code [14 marks — AO2 (3), AO3 (11)]
File handling (3 marks)
• Opens [Link] in read mode inside an outer try block (1)
• Catches FileNotFoundError (or equivalent) (1)
• Displays the exact message File [Link] not found (1)
Reading and validation (4 marks)
• Iterates through every line of the file (1)
• Strips whitespace / newline from each line (e.g. .strip()) (1)
• Inner try block wraps the integer conversion of each line (1)
• Catches ValueError, displays Skipped: <line> with the offending line content, and
continues processing remaining lines (1)
Tracking values (3 marks)
• Maintains a list (or running max/min/total/count) of valid integers (1)
• Correctly identifies the maximum integer (1)
• Correctly identifies the minimum integer (1)
Calculation and output (3 marks)
• Calculates the average correctly as total / count of valid integers (1)
• Formats the average to 2 decimal places (e.g. round(avg, 2), "{:.2f}".format(avg), or
f-string equivalent) (1)
• Displays the maximum, minimum, and average clearly labelled (1)
Structure (1 mark)
• File is closed properly after reading OR with open(...) construct used (1)
Example fully-correct answer:
try:
file = open("[Link]", "r")
numbers = []
for line in file:
line = [Link]()
try:
num = int(line)
[Link](num)
except ValueError:
print("Skipped: " + line)
[Link]()
maximum = max(numbers)
minimum = min(numbers)
average = sum(numbers) / len(numbers)
print("Maximum:", maximum)
print("Minimum:", minimum)
print("Average:", round(average, 2))
except FileNotFoundError:
print("File [Link] not found")
Expected output for the example file in Figure 2:
Skipped: abc
Skipped:
Skipped: 23.5
Maximum: 99
Minimum: 12
Average: 58.5
Common candidate errors and how to mark
• Catching ValueError outside the per-line loop — loses both inner-try marks because
subsequent valid lines won't be processed.
• Computing max/min/average inside the loop — accept if the final printed values are correct,
otherwise lose the corresponding mark.
• Using float() instead of int() — would accept 23.5 as valid, which contradicts the spec.
Lose the validation mark.
• Using a single broad except: — accept for the file-not-found mark only if it is structurally
clear which exception each branch is intended to handle.
• Hard-coding the file contents instead of reading from disk — score 0 across the board (no
file handling demonstrated).
04.2 Screen captures [1 mark]
• Screen capture shows the program running with the contents of Figure 2, displaying three
Skipped messages and the correct max/min/average values.