How to Wrap a Low Level Error in a Higher Level Exception in Python
Wrap low-level exceptions in a higher-level exception while preserving the original cause with the `from` keyword.
Python code
21 linesclass LowLevelError(Exception):
pass
class HighLevelError(Exception):
pass
def low_level_operation():
raise LowLevelError("storage drive failed to respond")
def high_level_operation():
try:
low_level_operation()
except LowLevelError as e:
raise HighLevelError(f"database operation failed: {e}") from e
if __name__ == "__main__":
try:
high_level_operation()
except HighLevelError as e:
print(f"Caught: {e}")
print(f"Cause: {e.__cause__}")
Output
Caught: database operation failed: storage drive failed to respond
Cause: storage drive failed to respond
How it works
The from e syntax chains exceptions, linking the original low-level error as the __cause__ of the new high-level one. This preserves the full diagnostic traceback while exposing a clean, domain-specific error to callers. The __cause__ attribute lets you inspect the root cause programmatically, and the traceback remains for debugging. This pattern is recommended by PEP 3134 for translating exceptions across abstraction layers.
Common mistakes
- Not using `from e`, losing the original cause in tracebacks
- Swallowing the low-level error entirely instead of wrapping it
- Raising a generic `Exception` instead of a domain-specific high-level exception
- Forgetting to include contextual info in the high-level message
Variations
- Use a custom `__init__` that stores the original exception as an attribute
- Use `raise ... from None` to suppress the cause if you want to hide it
Real-world use cases
- Wrapping database driver errors in a service-specific exception so UI code only handles one error type.
- Translating network timeout exceptions into an API-level retryable error for a client library.
- Converting filesystem low-level OSErrors into a business-logic exception in a backup tool.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.