Show understanding of an exception and the importance of exception handling

20.2 File Processing and Exception Handling

What is an Exception? 🚦

Think of a program like a road trip. An exception is a sudden traffic jam or a closed road that stops the car (your code) from moving forward. The program stops at that point unless you have a plan to get around it.

In programming, an exception is an event that disrupts the normal flow of instructions. It can be caused by a missing file, a wrong input, or a division by zero, among others.

Common File Exceptions in Python 🗂️

Exception When It Happens Typical Message
FileNotFoundError Trying to open a file that doesn’t exist. “No such file or directory”
PermissionError File exists but you don’t have read/write rights. “Permission denied”
IOError General input/output error. “I/O error”
UnicodeDecodeError Reading a file with the wrong encoding. “utf-8 codec can't decode byte …”

Handling Exceptions with try/except ??

  1. try – Wrap the risky code that might raise an exception.
  2. except – Catch the specific exception and decide what to do.
  3. else – (Optional) Code that runs if no exception occurs.
  4. finally – (Optional) Code that runs no matter what, e.g., closing a file.

Example: Reading a file safely.

try:
    with open('data.txt', 'r') as f:
        content = f.read()
except FileNotFoundError:
    print("❌ The file was not found. Please check the path.")
except PermissionError:
    print("❌ Permission denied. Try running as administrator.")
else:
    print("??
 File read successfully!")
finally:
    print("🔚 Finished file operation.")
  

Why Exception Handling Matters 🎯

  • Robustness – Your program keeps running even when something goes wrong.
  • User Experience – Friendly error messages help users understand what happened.
  • Security – Prevents leaking sensitive information by catching and sanitising errors.
  • Debugging – Clear exception types make it easier to locate bugs.

Exam Tips for 20.2 📚

  • Define an exception – Use the traffic‑jam analogy to explain why it interrupts the flow.
  • List common file exceptions – Show the table or list them with brief triggers.
  • Show try/except syntax – Write a short code snippet that includes try, except, else, and finally.
  • Explain the purpose of finally – Mention resource cleanup (e.g., closing files).
  • Use emojis or analogies – Makes answers memorable and shows understanding.

Revision

Log in to practice.

2 views 0 suggestions