Learning Objectives
By the end of this topic you will be able to:
Use file handling operations: open, read, write, close in OCR pseudo-code and Python
Distinguish between sequential, random and binary file access
Explain exception handling and write try/catch/finally constructs
Identify common exceptions and explain why robust programs must handle them
File Handling Basics
File Operations
Files are used for persistent storage — data that survives after the program ends. OCR H446 expects you to know the four core file operations: open, read, write, close.
OCR Pseudo-Code
openFile("data.txt", READ)
line ← readLine("data.txt")
while NOT endOfFile("data.txt")
line ← readLine("data.txt")
endwhile
closeFile("data.txt")
Python Equivalent
f = open("data.txt", "r")
for line in f:
print(line.strip())
f.close()
# Or use: with open() as f
Exception Handling
Exceptions and Error Handling
An exception is a runtime error — an unexpected event that disrupts normal program execution. Without handling, an exception causes the program to crash. Exception handling allows the program to respond gracefully.
Try / Catch / Finally
try
x ← int(input("Number: "))
except
print("Invalid input")
finally
print("Done")
endtry
Execution Flow
try: code that might raise an exception
except/catch: executes ONLY if an exception occurs
finally: executes ALWAYS — whether an exception occurred or not. Used to release resources (e.g. close a file).
Common Exceptions
Exception Types You Must Know
ValueError: raised when a function receives an argument of the right type but an invalid value. E.g. int("hello") — "hello" is a string (right type for input) but cannot be converted to int.
IndexError / KeyError: accessing an index outside a list's range (IndexError) or a key that doesn't exist in a dictionary (KeyError). Both cause crashes if unhandled.
FileNotFoundError / IOError: attempting to open a file that doesn't exist or cannot be accessed (permissions, drive not connected). Essential to handle in any file-handling program.
ZeroDivisionError: division or modulo by zero. Particularly common when dividing by user-supplied values that might be zero.
Robust Programs
Why Handle Exceptions?
Programs that crash on unexpected input are not robust or user-friendly. Real-world programs must handle all realistic failure modes — invalid user input, missing files, network failures, hardware errors — and continue running or fail gracefully with a helpful message.
The finally block is critical for resource management — it guarantees a file is closed even if an exception occurs mid-read. Without this, file handles can be left open, leading to resource leaks or file corruption.
In Python, the with statement provides a context manager that automatically closes files when the block exits — even if an exception occurs. This is preferred over manual open/close because it's safer and more readable.
Common Mistakes
Don't Lose Marks
!
Forgetting to close the file — many students write code that opens and reads a file but omits closeFile(). OCR mark schemes specifically look for file closure. In finally blocks or Python's with statement, this is handled automatically — mention it.
!
Saying the finally block runs only if no exception occurs — this is the opposite of what finally does. Finally ALWAYS runs — its entire purpose is to guarantee cleanup code (like closing files) executes regardless of exceptions.
!
Not distinguishing between sequential and random access — sequential access reads in order; random access uses a calculated position to jump directly to a record. Students often describe random access as "accessing data in a random order" rather than "accessing by calculated position".