Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Errors & context managersMiddleCommonPractical

Convert a low-level `KeyError` into a domain-specific configuration error without losing the original traceback cause.

Answer

Define a domain exception and catch only the low-level error you intend to translate. Raise the domain exception with `from exc` so Python records the original failure as `__cause__`. Callers then have a stable application-level exception to catch, while debugging still shows exactly which low-level key lookup failed.

Strong answer includes

  • defines a domain-specific exception
  • catches only the intended low-level exception
  • uses raise ... from exc for explicit chaining

Practical example

Explicit exception chaining
Python
editable · browser sandbox
Result
Run the code to see the result.

The caller sees the domain exception while `__cause__` keeps the original KeyError explicitly attached.

Expected result: KeyError, then Missing required key: token.

#exceptions#chaining#error-handling

Sources

Errors and ExceptionsPython Software Foundation · try/except/else/finally control flow and exception chainingThe Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics