Back to Course
Python Essentials: The Engineering Approach
Module 11 of 20
11. Error Handling
EAFP (Easier to Ask for Forgiveness than Permission)
Pythonic code prefers try/except over checking conditions.
Non-Pythonic:
pythonif os.path.exists("file.txt"): open("file.txt")
Pythonic:
pythontry: open("file.txt") except FileNotFoundError: print("Missing file")
Why? Because between the check and the open, the file could disappear (Race Condition).
The finally Block
Always runs. Used for cleanup (closing files, DB connections).