Skip to the solution
MediumDSA12 min read

How do you create and chain custom exceptions?

724 views

The problem

Question presented to candidate: "Say you are writing a payments library. How would you design its exceptions, and when one of your functions catches a low-level error like a ValueError, how do you raise your own error without losing the original one?"

What a strong answer should cover:

  • Subclass Exception (not BaseException), give the library one base class so callers can catch everything with one clause, and add specific subclasses for errors callers handle differently
  • Extra data goes in attributes set in __init__, with every argument passed on to super().__init__ so args, str() and pickling keep working; override __str__ only for the message
  • raise New(...) from original sets __cause__ (explicit chaining); raising inside an except block sets __context__ automatically (implicit chaining); the traceback wording differs
  • raise New(...) from None sets __suppress_context__ so the internal error is hidden from the traceback but still kept on __context__
  • add_note() (3.11+, PEP 678) attaches extra context to an exception after it was raised
  • Chaining dates from PEP 3134 (Python 3.0) and from None from PEP 415 (3.3)

Clarifying questions expected:

  • Who catches these errors: application code, an HTTP layer that maps them to status codes, or both?
  • Do the errors need to cross process boundaries (multiprocessing, task queues), which requires pickling?

Code / implementation expected: Yes β€” a small hierarchy with one attribute-carrying subclass, and a function that translates a built-in error with raise ... from e.

  • exceptions
  • custom

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

12 min read Β· 11 sections

Run the code

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

PythonA custom hierarchy, and __cause__ / __context__ for the three ways to chain
PythonWhat the traceback says for each chain, add_note, and the pickling trap

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 72 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

How does an LRU cache work internally?

Continue