Python - Errors & Exceptions
Overview
Estimated time: 35–45 minutes
Handle errors robustly with Python’s exception system. Learn the EAFP vs LBYL philosophy and when to log vs raise.
Learning Objectives
- Use try/except/else/finally to manage errors.
- Choose EAFP or LBYL appropriately.
- Decide when to log and when to raise exceptions.
Prerequisites
try/except/else/finally
try:
n = int(input("Number: "))
except ValueError:
print("Not a number")
else:
print(n * 2)
finally:
print("done")
Sample Run:
Number: x\nNot a number\ndone
EAFP vs LBYL
# LBYL (Look Before You Leap)
s = input("Enter integer: ")
if s.isdigit():
print(int(s) * 2)
else:
print("Not a number")
# EAFP (Easier to Ask Forgiveness than Permission)
try:
print(int(s) * 2)
except ValueError:
print("Not a number")
Common Pitfalls
- Broad except clauses hiding bugs; prefer specific exceptions.
- Logging and re-raising the same exception multiple times (duplicate signals).
Checks for Understanding
- What is the difference between EAFP and LBYL?
- Why avoid bare
except:
?
Show answers
- EAFP tries and handles exceptions; LBYL checks before doing.
- It masks all exceptions including KeyboardInterrupt/SystemExit; use specific exceptions.
Exercises
- Open a file given by the user and handle the case where it does not exist.
- Convert a list of strings to integers using EAFP; skip invalid entries with a warning.