Exceptions
Exceptions
Exceptions are objects derived from BaseException; application errors inherit from Exception. Candidates must master try/except/else/finally ordering: else runs only if no exception occurred, and finally always runs, even after return or an uncaught exception. Multiple except clauses are checked top to bottom, so put specific exceptions before general ones.
Key concepts: raising with raise ValueError("msg"), re-raising with bare raise, chaining via raise New from old (sets __cause__), and the implicit __context__. Custom exceptions typically subclass Exception. except (A, B) as e: catches both; the as name is deleted after the block. Exception does not catch KeyboardInterrupt or SystemExit (those are BaseException subclasses).
Traps: a finally block containing return overrides any exception or earlier return-a common output-prediction question. Ordering matters: except Exception before except ValueError makes the latter unreachable. Also watch for exceptions raised inside except blocks and whether else is skipped. assert raises AssertionError and is disabled with -O.
Worked example:
def f():
try:
return "try"
finally:
return "finally"
f() returns "finally" because the finally return discards the pending return value. Rule of thumb: finally always wins; specific handlers first; else only on success.