20.2 File Processing and Exception Handling

Bulk view disabled for Guests. View lessons individually.

File & Exception Handling

1. Exception Handling

An Exception is a runtime error that disrupts the normal flow of a program. Handling them prevents the program from crashing.

try: number = int(input("Enter a divisor: ")) result = 100 / number print("Result is:", result) except ValueError: # Triggered if input is not an integer print("Error: Please enter a valid number.") except ZeroDivisionError: # Triggered if user enters 0 print("Error: Cannot divide by zero.") except Exception as e: # Catch-all for any other unexpected errors print("An unexpected error occurred:", e) finally: # This block ALWAYS runs (e.g., to close a database connection) print("End of operation.")

2. File Handling (Text Files)

In A-Level, you must know how to Read, Write, and Append to files. We use the with statement as it is safer (automatically closes the file).

# WRITING TO A FILE ('w' overwrites, 'a' appends) def write_to_file(filename, data): with open(filename, "w") as file: file.write(data + "\n") # READING FROM A FILE def read_from_file(filename): try: with open(filename, "r") as file: # .readlines() returns a list of all lines lines = file.readlines() for line in lines: print(line.strip()) # .strip() removes newline characters except FileNotFoundError: print("Error: The file was not found.") # Example Usage write_to_file("students.txt", "John Doe") read_from_file("students.txt")

3. Random Access (Binary Files)

A2 requires understanding Binary Files for records (Random Access). Python uses the pickle module to save objects directly.

import pickle class Student: def __init__(self, name, score): self.name = name self.score = score # Saving an object to a binary file student_obj = Student("Nanjala", 85) with open("data.dat", "wb") as file: pickle.dump(student_obj, file) # Loading an object with open("data.dat", "rb") as file: loaded_student = pickle.load(file) print(loaded_student.name)
⚠️ Exam Note (Paper 4):

Always combine File Handling with Exception Handling. If the question asks to read from a file, you should wrap it in a try...except FileNotFoundError block to earn "Robustness" marks.