This guide explains exception chaining with raise ... from ... through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
raise NewError(...) from original_error records the original exception as an explicit cause. This preserves diagnostic context while presenting a higher-level message to callers.
When and Why to Use It
The following example focuses on a practical use of Exception Chaining with raise ... from .
Step-by-Step Example
def parse_quantity(text):
try:
return int(text)
except ValueError as error:
raise ValueError("Quantity must be numeric") from error
try:
parse_quantity("many")
except ValueError as error:
print(error, type(error.__cause__).__name__)
Understanding the Example
The outer error says Quantity must be numeric, and its __cause__ points to the original ValueError raised by int.
Expected Output
Quantity must be numeric ValueError
Important Behavior and Edge Cases
Do not discard the original exception when investigating failures across application layers; chaining helps preserve the cause.
Try It Yourself
Wrap a failed configuration integer conversion and print the __cause__ type.
Common Beginner Mistakes
- Do not discard the original exception when investigating failures across application layers; chaining helps preserve the cause.
- Handling the symptom rather than identifying the failing operation, or letting a broad exception handler hide defects.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- raise NewError(...) from original_error records the original exception as an explicit cause.
- The outer error says Quantity must be numeric, and its __cause__ points to the original ValueError raised by int.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.