Working with Modules and Handling Exceptions
Estimated study time: 11 minutes.
Two skills separate beginner code from production-ready code: organizing logic into modules, and anticipating failure with proper exception handling.
Working with Modules
A module is simply a single file containing related code — functions, classes, or variables — that can be imported elsewhere. Splitting a project into modules makes it easier to test, debug, and reuse individual pieces.
# file: calculator.py
def add(a, b):
return a + b
# file: main.py
from calculator import add
print(add(4, 5))
Handling Exceptions
Not every operation succeeds — a file might not exist, a network call might time out, or user input might be invalid. Exception handling lets your program respond gracefully instead of crashing.
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero:", e)
finally:
print("Cleanup runs regardless of the outcome.")
Best Practices
- Catch specific exception types rather than a bare
except. - Use
finallyfor cleanup code that must always run. - Don't use exceptions for routine control flow — reserve them for genuinely exceptional cases.
💡 Tip: Log the full exception details during development, but show the user a clean, friendly message in production.