Working with Modules and Handling Exceptions
Build reusable modules and write Python code that fails gracefully, not silently.
Two skills separate a beginner Python script from production-ready code: organizing logic into modules, and handling errors through proper exception handling. Together, they make your data pipelines reusable and resilient.
Creating Your Own Module
Any Python file can become a module. Save reusable functions in utils.py, then import them elsewhere in your project.
# utils.py
def clean_text(value):
return value.strip().lower()
# main.py
from utils import clean_text
print(clean_text(" Hello World "))
Why Exceptions Happen
Errors — missing files, bad data types, division by zero — are inevitable when working with real datasets. Python raises an exception whenever it encounters something it can't process, and unhandled exceptions crash your program.
Try, Except, Else, Finally
try:
result = 10 / int(user_input)
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Please enter a valid number.")
else:
print("Result:", result)
finally:
print("Execution completed.")
ValueError) instead of a bare except: — it keeps bugs from hiding silently.Best Practices
- Only wrap the code that can actually fail inside
try - Use
finallyto close files or database connections - Raise custom exceptions with
raise ValueError("message")when validating data
Mastering this combination means your data scripts keep running — and tell you exactly what went wrong — instead of crashing without explanation.