Monday, March 16, 2026

Lesson 8: File Handling and Exception Handling | Coding Class Series



Lesson 8: File Handling and Exception Handling | Coding Class Series

Introduction

Welcome to Lesson 8!
In this lesson, we will learn about file handling in Python and how to manage errors using exception handling. These skills are essential to make your programs robust and data-driven.


1. File Handling

File handling allows your program to read from and write to files on your computer.

Opening a file:

file = open("example.txt", "w")  # 'w' mode to write
file.write("Hello, Python!")
file.close()

Reading a file:

file = open("example.txt", "r")  # 'r' mode to read
content = file.read()
print(content)  # Output: Hello, Python!
file.close()

Using with statement (recommended):

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

File Modes:

  • r → read
  • w → write (overwrite)
  • a → append
  • rb / wb → read/write binary

2. Exception Handling

Exceptions occur when your program runs into an error.
Python allows you to handle exceptions gracefully using try, except, finally blocks.

Example:

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input! Enter a number.")
finally:
    print("Execution completed.")

Key Points:

  • try: Block where error might occur
  • except: Handles specific errors
  • finally: Executes always, even if an error occurs

3. Combining File Handling and Exceptions

You can handle file errors with exception handling:

try:
    with open("data.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found. Please check the file name!")

Benefits:

  • Prevents program crashes
  • Provides useful error messages
  • Improves program reliability

4. Practice Exercises

  1. Create a file notes.txt and write 5 lines of text in it.
  2. Read the file and count the number of words.
  3. Write a program that asks the user for a filename and prints its content. Handle errors if the file does not exist.
  4. Create a program that divides two numbers and handles division by zero and invalid input using exception handling.


No comments:

Post a Comment