This guide explains error handling anti-patterns to avoid 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
Common error-handling anti-patterns include broad silent catches, catching an exception only to ignore it, returning success after failure and protecting too much unrelated code in one try block.
When and Why to Use It
The following example focuses on a practical use of Error Handling Anti-Patterns to Avoid.
Step-by-Step Example
def parse_price(text):
try:
return float(text)
except ValueError:
return None
print(parse_price("10.50"))
print(parse_price("not a price"))
Understanding the Example
The helper returns 10.5 for valid text and None for invalid text, making failure visible to the caller instead of pretending the invalid input was zero.
Expected Output
10.5
None
Important Behavior and Edge Cases
A return value of None must be part of a documented contract. For higher-level APIs, raising ValueError may be safer than silently continuing.
Try It Yourself
Find an except Exception: pass statement in sample code and replace it with deliberate error reporting.
Common Beginner Mistakes
- A return value of None must be part of a documented contract. For higher-level APIs, raising ValueError may be safer than silently continuing.
- 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
- Common error-handling anti-patterns include broad silent catches, catching an exception only to ignore it, returning success after failure and protecting too much unrelated code in one try block.
- The helper returns 10.5 for valid text and None for invalid text, making failure visible to the caller instead of pretending the invalid input was zero.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.