- Home
- Interview Questions
- Python
- 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
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 setsX.__cause__ = YandX.__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__toNoneand__suppress_context__toTrue, 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 aKeyErrorfrom 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 shownIf 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
exceptwithoutfrom. The root cause is kept, but the traceback wording suggests a second bug occurred during handling. - Using
from Noneeverywhere to make tracebacks look clean. This throws away the most useful debugging information in production logs. - Confusing
raisewithraise err. A bareraisere-raises the active exception unchanged.raise errre-raises the same object but adds the current line to the traceback, which is noisier and easy to misuse outside anexceptblock. - 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
ExceptionGroupandexcept*, and when do they appear (for example, withasyncio.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
Related Questions
- In what order do try, except, else and finally blocks run in Python? · Python · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- Why does using a mutable default argument like a list cause bugs in Python? · Python · 1 ans
- How do positional-only (/) and keyword-only (*) parameters work in Python function signatures? · Python · 1 ans
- What is broadcasting in NumPy and what rules decide whether two arrays can be combined? · Python · 1 ans
- Why does Pandas raise SettingWithCopyWarning and how do you fix chained assignment correctly? · Python · 1 ans
- What is the difference between assignment, shallow copy and deep copy in Python? · Python · 1 ans
- Why do lambdas created inside a loop all return the last loop value in Python? · Python · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)