3.2.7 File Handling
Programs often need to read data from files (persistent storage) and write data to files. Variables are lost when a program ends — files allow data to persist between runs.
Why use files?
- Store data permanently (survives when the program closes)
- Share data between different programs
- Handle large amounts of data not suited to hard-coded arrays
AQA File Operations
| Operation | AQA Pseudo-code | Purpose |
| Open for reading | openRead("file.txt") | Opens file; reads content |
| Open for writing | openWrite("file.txt") | Opens file; overwrites content |
| Open for appending | openAppend("file.txt") | Opens file; adds to end |
| Read a line | readLine(myFile) | Returns next line as string |
| Write a line | writeLine(myFile, text) | Writes text + newline |
| End of file check | endOfFile(myFile) | Returns True when no more lines |
| Close file | close(myFile) | Releases the file resource |
Reading from a File
myFile ← openRead("students.txt")
WHILE NOT endOfFile(myFile)
line ← readLine(myFile)
OUTPUT line
ENDWHILE
close(myFile)
Writing to a File
myFile ← openWrite("scores.txt")
writeLine(myFile, "Alice,95")
writeLine(myFile, "Bob,78")
close(myFile) // ALWAYS close the file
Appending to a File
myFile ← openAppend("log.txt")
writeLine(myFile, "New entry added")
close(myFile)
// openWrite would DELETE existing content; openAppend preserves it
3.2.9 Exception Handling
An exception is a run-time error — something unexpected that causes a program to crash. Exception handling allows your code to detect and respond to errors gracefully, rather than crashing.
Common run-time errors
| Error type | Example cause |
| Division by zero | result ← 10 DIV 0 |
| File not found | openRead("missing.txt") |
| Type mismatch | int("abc") — converting non-numeric string |
| Array out of bounds | Accessing index beyond array size |
TRY / EXCEPT in AQA
AQA uses TRY and EXCEPT to handle exceptions:
TRY
value ← int(INPUT("Enter a number: "))
result ← 100 DIV value
OUTPUT result
EXCEPT
OUTPUT "Error: invalid input or division by zero"
ENDTRY
File handling with exception handling
TRY
myFile ← openRead("data.txt")
line ← readLine(myFile)
OUTPUT line
close(myFile)
EXCEPT
OUTPUT "File could not be opened"
ENDTRY
Exam tip: Always close files after use — openWrite overwrites the entire file, openAppend adds to it. The WHILE NOT endOfFile() loop is the standard pattern for reading all lines from a file.
⚠️ Common Mistakes
- Forgetting to close the file after reading or writing
- Using openWrite when you want to add data — this deletes existing content
- Not checking endOfFile() in the WHILE condition — causes an error when reading past the end
- Thinking TRY/EXCEPT prevents all errors — it only handles them at runtime