1. Home
  2. Interview Questions
  3. Python
  4. What is exception chaining in Python and when should you use…

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: Exception chaining links a new exception to the one that caused it. Python records the original automatically in __context__ when you raise inside an except block. raise NewError from original sets __cause__ explicitly and marks it as the direct cause. raise ... from None hides the original from the traceback.

Detailed explanation

In real applications you often catch a low-level error, such as KeyError, OSError or a database driver error, and raise a higher-level, domain-specific one, such as ConfigError or PaymentFailed. Chaining keeps the root cause attached, so the person debugging sees both errors.

There are three behaviours you should be able to explain:

  • Implicit chaining. When any exception is raised while another is being handled, Python stores the earlier one in the new exception's __context__. The traceback shows both, joined by "During handling of the above exception, another exception occurred". This message suggests that a second, accidental failure happened, which is misleading if the translation was intentional.
  • Explicit chaining with raise X from Y. This sets X.__cause__ = Y and X.__suppress_context__ = True. The traceback reads "The above exception was the direct cause of the following exception", which correctly says that you deliberately converted the error.
  • Suppression with raise X from None. This sets __cause__ to None and __suppress_context__ to True, so the traceback shows only the new exception. The original is still stored in __context__ if you need it. Use this when the original error is an internal detail that adds noise, for example a KeyError from a lookup table behind a public API.

Use this as a guideline:

  • When you translate exceptions at a module or library boundary, use raise ... from err.
  • When the underlying error would confuse callers or leak internal details, use from None. Do this sparingly.
  • When you only want to log and propagate the same error, use a bare raise. It re-raises the current exception with its original traceback, and no chaining is needed.

Example

class ConfigError(Exception):
    pass

def load_port(cfg):
    try:
        return int(cfg['port'])
    except KeyError as err:
        raise ConfigError('port missing in config') from err
    except ValueError:
        raise ConfigError('port must be an integer') from None

try:
    load_port({})
except ConfigError as e:
    print(repr(e))                 # ConfigError('port missing in config')
    print(repr(e.__cause__))       # KeyError('port')
    print(e.__suppress_context__)  # True

try:
    load_port({'port': 'abc'})
except ConfigError as e:
    print(e.__cause__)             # None
    print(repr(e.__context__))     # ValueError(...) still stored, just not shown

If the first case were left uncaught, the traceback would show the KeyError first, then the "direct cause" line, then the ConfigError. Callers can catch one domain exception, and developers still see the real reason.

Common mistakes

  • Raising a new exception inside except without from. The root cause is kept, but the traceback wording suggests a second bug occurred during handling.
  • Using from None everywhere to make tracebacks look clean. This throws away the most useful debugging information in production logs.
  • Confusing raise with raise err. A bare raise re-raises the active exception unchanged. raise err re-raises the same object but adds the current line to the traceback, which is noisier and easy to misuse outside an except block.
  • Wrapping with a generic Exception('failed') instead of a meaningful custom exception class. Callers then cannot catch it selectively.

Follow-up questions

  • How would you design a custom exception hierarchy for a library?
  • What are ExceptionGroup and except*, and when do they appear (for example, with asyncio.TaskGroup)?
  • How does add_note() on exceptions help when you want to add context without wrapping?

Interview tip: Frame your answer around a real boundary, such as a repository layer converting a database driver error into a domain error with raise ... from err. Interviewers want to see that you think about who catches the exception and who debugs it.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More hard Python questions

All hard questions →

Related Questions

‹
Q4 of 10 · Python
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA