Skip to content
Streak:0Loading your progress…Sign in

Module 4 · Lesson 2 of 3

Exceptions

try/except/else/finally, custom exceptions, and EAFP. ~20 min

Lesson notes

Coming from TypeScript

TypeScript

try { risky(); }
catch (e) { if (e instanceof NotFound) {...} else throw e; }
finally { cleanup(); }

Python

try:
    risky()
except NotFound as e:
    ...
except (TimeoutError, ConnectionError):
    ...
else:
    ...   # runs only if no exception
finally:
    cleanup()

Python culture prefers EAFP ("easier to ask forgiveness than permission"): try the operation and catch the specific error, rather than checking first. Never write bare except: — it also catches KeyboardInterrupt. Use raise NewError(...) from err to keep the cause chain.

Practice

  1. 1. Parse config with custom errors

    medium25 XP

    Define class ConfigError(Exception). Write parse_port(env: dict) -> int that reads env["PORT"], converts to int, and checks 1–65535. Raise ConfigError with a helpful message in every failure case (missing, not a number, out of range), chaining the original exception where there is one.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor