Exception Handling in Python
🔹 Introduction
An exception is an error that occurs during program execution and stops the program if it
is not handled.
For example:
a = 10
b = 0
print(a / b) # ❌ ZeroDivisionError
This causes the program to stop because division by zero is not allowed.
To prevent the program from crashing, we use exception handling.
🔹 Using try and except
The try block contains code that might cause an error.
The except block contains code that runs when an error occurs.
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Result =", a / b)
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Please enter only numbers!")
✅ If no error occurs, the except block is skipped.
✅ If an error occurs, the matching except block runs.
🔹 Using finally block
The finally block runs every time — whether an exception occurs or not.
It is mostly used to release resources (like closing files or database connections).
try:
f = open("[Link]", "r")
content = [Link]()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
[Link]()
print("File closed successfully.")
✅ Even if an error occurs, finally will still run.
🧠 Summary Table
Block Purpose
try Code that may cause an error
except Code to handle the error
finally Code that always runs (cleanup)
📁 File Handling in Python
Python allows programs to store data permanently using files.
🔹 Types of Files
Type Description Example
Text File Stores data as readable text (characters) .txt, .csv
Binary File Stores data in binary form (0s and 1s), not human-readable .dat, .bin
CSV File Comma Separated Values file; stores tabular data .csv
🔹 Opening and Closing Files
Files are opened using the open() function and closed using close().
file = open("[Link]", "r") # open file for reading
data = [Link]()
print(data)
[Link]()
Mode Meaning
"r" Read (default)
"w" Write (overwrites old data)
"a" Append (adds new data at the end)
🔹 Writing to a Text File
f = open("[Link]", "w")
[Link]("Hello Students!\nWelcome to Python file handling.")
[Link]()
🔹 Reading from a Text File
f = open("[Link]", "r")
print([Link]())
[Link]()
🔹 Working with CSV Files
You can use the csv module to work with comma-separated files.
import csv
with open("[Link]", "w", newline="") as f:
w = [Link](f)
[Link](["Name", "Marks"])
[Link](["Aarti", 90])
🔹 Absolute and Relative Paths
Absolute Path – full path from the root directory.
Example:
"C:/Users/Aarti/Documents/[Link]"
Relative Path – path relative to the current working directory.
Example:
"[Link]" (file is in the same folder as your Python program)
🧠 In Short
Concept Explanation
Text file Human-readable text
Binary file Machine-readable (images, audio, etc.)
CSV file Comma-separated values
Absolute path Full location from root
Relative path Shorter path from current folder