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.

Easy Python 3.0+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

21 lines
Python 3.0+
class 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

stdout
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

  1. Use a custom `__init__` that stores the original exception as an attribute
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.