Question presented to candidate: "Walk me through how exception handling works in Python. What do try, except, else and finally each do, in what order do they run, and how does Python decide which except clause handles an error?"
What a strong answer should cover:
- An exception is an object (an instance of a class derived from
BaseException) that stops normal execution and travels up the call stack until a matchingexceptclause handles it - The four clauses:
tryholds the risky code,excepthandles matching errors,elseruns only whentryraised nothing,finallyruns on every way out (normal end,return, or an error passing through) - Matching is by
isinstance, clauses are tested top to bottom, the first match wins, so specific classes go before their base classes; a tuple catches several types - Catch
Exception, not a bareexcept:(which also catchesKeyboardInterruptandSystemExit); keep thetryblock small; use bareraiseto re-raise unchanged - The
as ename is deleted when theexceptblock ends, and areturninsidefinallysilently discards an in-flight exception - CPython detail: since 3.11 a
trycosts almost nothing when no exception is raised ("zero-cost" exceptions, via an exception table instead of setup instructions)
Code / implementation expected: Optional β a short try/except/else/finally function showing which clauses run for success and for failure.