Python - Try...Except
Overview
Estimated time: 20–30 minutes
Handle errors gracefully with try/except/else/finally. Learn when to catch, when to let exceptions propagate, and how to raise your own.
Learning Objectives
- Use try/except/else/finallyproperly.
- Create and raise custom exceptions.
- Apply EAFP vs LBYL and avoid broad excepts.
Prerequisites
Basic structure
try:
    x = int(input("Enter an integer: "))
except ValueError as e:
    print("Not an integer", e)
else:
    print("You entered", x)
finally:
    print("always runs")
Raising and chaining
def parse_age(s: str) -> int:
    try:
        return int(s)
    except ValueError as e:
        raise ValueError(f"invalid age: {s}") from e
Custom exceptions
class ConfigError(Exception):
    pass
raise ConfigError("missing DB_URL")
Common Pitfalls
- Using bare except:; catch specific exceptions instead.
- Swallowing exceptions without logging or re-raising; this hides bugs.
Checks for Understanding
- When does the elseblock run?
- How do you preserve the original traceback when raising a new error?
Show answers
- When no exception was raised in the tryblock.
- Use raise ... from eto chain exceptions.
Exercises
- Wrap file opening and parsing in a try/exceptwith a helpful error message.
- Create a custom exception type for invalid configuration and raise it when an env var is missing.