SLIDE 1 / 10
CSZone.co.uk
OCR H446 · Component 2 · 2.2.1

File Handling &
Exception Handling

OCR A Level Computer Science · cszone.co.uk
H446 SpecA Level
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
File Access Modes

Types of File Access

Sequential Access
Records read in order from beginning to end. To find a specific record, must read all preceding records. Simple; used for text files, log files. Must re-open the file to start again.
Random (Direct) Access
Records can be accessed in any order using a record number or key. Records must be fixed length so the position can be calculated. Used in databases and index files. Much faster for large files.
Binary Files
Store data as raw bytes rather than human-readable text. Images, audio, compiled programs are binary files. More compact and efficient than text but not human-readable. Accessed using binary read/write operations.
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.
Exam Practice
OCR H446 Style · 5 marks
A program reads temperature readings from a file and calculates the average. Write pseudo-code for the file reading section that includes appropriate exception handling, and explain the purpose of the finally block.
[5 marks]
3
try
  openFile("temps.txt", READ)
  total ← 0 : count ← 0
  while NOT endOfFile("temps.txt")
    line ← readLine("temps.txt")
    total ← total + real(line)
    count ← count + 1
  endwhile
except
  print("Error reading file or invalid data")
finally
  closeFile("temps.txt")
endtry
2
The finally block ensures the file is always closed regardless of whether an exception occurred. This prevents resource leaks and file corruption. Without it, if an exception is thrown mid-read, the file may remain open.
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".
2.2.1b Complete
Well done! ✓
File Handling and Exception Handling
Return to lesson to continue