EXCEPTION HANDLING
AND FILE HANDLING IN
PYTHON
WHY HANDLE
EXCEPTIONS?
Exceptions are unexpected errors that occur during
program execution, such as dividing by zero or accessing
a missing file. Without proper handling, these errors crash
your program abruptly.
Exception handling allows you to catch these errors
gracefully, provide meaningful feedback to users, and
keep your application running smoothly.
Proper error handling improves program reliability and
user experience, making your code more robust and
professional.
2
TRY EXCEPT BASICS
Wrap risky code in a try block.
If an error occurs, the except block catches it and prevents your program
from crashing.
Always catch specific exceptions like ZeroDivisionError for precise
handling.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
3 — This catches the division error gracefully instead of
terminating the program unexpectedly.
THE FINALLY BLOCK
Code in the finally block runs no matter what—whether an exception
occurs or not.
Key Point: The finally block executes even if an exception is raised
and not handled, ensuring your cleanup code always runs. Always
use finally or with-statements to prevent resource leaks.
4
CREATING CUSTOM EXCEPTIONS
Why create custom exceptions? Tailor error handling to your
application's specific logic. Define meaningful error types that
make debugging easier and code more readable.
Basic syntax:
class NegativeValueError(Exception): pass
Example:
def check_positive(x):
if x < 0:
raise NegativeValueError("Negative value not allowed")
Tip: Always provide meaningful error messages that help
5 identify the problem quickly.
FILE HANDLING IN
PYTHON
File handling is essential for storing persistent data, reading
configurations, processing datasets, and much more.
7
INTRODUCTION TO FILE
HANDLING
Files store persistent data outside program memory, allowing
information to survive after a program ends.
Common file types include text files, CSV for tabular data,
JSON for structured data interchange, and binary formats like
pickle.
Basic operations involve open, read, write, and close. Python
supports multiple modes: read ('r'), write ('w'), append ('a'),
and binary ('b') for different use cases.
8
WORKING WITH TEXT
FILES
Opening and Writing: Use open() with mode 'w' for writing or 'r' for
reading. The with-statement ensures automatic file closing,
preventing resource leaks and errors.
Reading Content: Use [Link]() for entire file, [Link]() for single
lines, or [Link]() for a list. Always use with open() for safe,
clean file handling.
9
HANDLING CSV FILES
CSV (Comma Separated Values) is a common format for tabular data.
Python's csv module makes reading and writing CSV files simple:
import csv
with open("[Link]") as f:
reader = [Link](f)
for row in reader:
print(row)
CSV vs Text Files: CSV provides structured, column-
based data ideal for spreadsheets and databases.
Text files store unstructured content.
Use [Link]() for parsing and [Link]() for
10 creating CSV files with proper formatting.
JSON FILE HANDLING
JSON (JavaScript Object Example:
Notation) is a popular
format for data with open("[Link]", "w") as f:
interchange. [Link]({"name": "Alice", "age": 22}, f)
Use Python's json module [Link](f).
with [Link]() to write
and [Link]() to read
JSON files.
Perfect for configuration files, APIs, and
structured data storage.
11
PICKLE MODULE FOR
OBJECT SERIALIZATION
Pickle is Python's built-in binary format for serializing and
deserializing complex objects like lists, dictionaries, and class
instances.
It allows you to save entire Python objects to files and reload
them later with their structure intact.
Security Warning: Pickle files are not human-readable
and can execute arbitrary code when loaded. Never
12 unpickle data from untrusted sources. Use pickle only
with data you have created or from trusted origins.
QUESTIONS !