Exception chaining preserves the reason behind a higher-level failure. Domain boundaries can add context without discarding the original cause.
Before you start
You should know Python functions, collections and exceptions. Use a small isolated script or interactive session to trace the example. Pay attention to when objects are created and when work executes; iteration, binding and mutation can happen at different points in a program.
The practical goal is to reason through this situation: Raise an import failure from the underlying parser exception. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Add operation context
Identify the domain operation that failed, not only the low-level parser message.
Step 2: Preserve the cause
Raise the higher-level exception from the original exception.
Step 3: Control public output
Expose a safe message while retaining traceback and cause internally.
Worked scenario
Raise an import failure from the underlying parser exception.
try:
number = int('invalid')
except ValueError as error:
raise RuntimeError('Unable to parse record quantity') from errorThe outer exception adds context without deleting the ValueError. The invalid input need not be copied into a public response or log containing sensitive records.
Common mistake
Replacing errors with generic strings loses the traceback and cause.
Verify the behavior
Inspect the cause and traceback; verify public error mapping excludes sensitive input.
Interview exercise
Expose a safe user message.
Answer and reasoning
Return a stable public error while preserving detailed chained diagnostics internally without leaking sensitive input.
Continue learning
Compare the scenario with the Python interview questions and test your understanding with the Python MCQs. For terminology and implementation details, consult the reference material.