Skip to the solution
EasyDSA11 min read

How does exception handling work in Python?

87 views

The problem

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 matching except clause handles it
  • The four clauses: try holds the risky code, except handles matching errors, else runs only when try raised nothing, finally runs 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 bare except: (which also catches KeyboardInterrupt and SystemExit); keep the try block small; use bare raise to re-raise unchanged
  • The as e name is deleted when the except block ends, and a return inside finally silently discards an in-flight exception
  • CPython detail: since 3.11 a try costs 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.

  • exceptions

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 13 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythontry / except / else / finally: which clause runs when
PythonThe hierarchy, clause order, the deleted as-name, bare raise and finally traps

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 34 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is the difference between shallow and deep copy?

Continue