This guide explains raise statement: throw your own exceptions 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 deliberately signals an error when input violates an operation’s contract. Built-in exception classes should be preferred unless a distinct application-specific error is needed.
When and Why to Use It
The following example focuses on a practical use of raise Statement: Throw Your Own Exceptions.
Step-by-Step Example
def calculate_percentage(part, total):
if total <= 0:
raise ValueError("Total must be positive")
return part / total * 100
try:
print(calculate_percentage(5, 0))
except ValueError as error:
print(error)
Understanding the Example
The invalid denominator is rejected before any division occurs. The handler receives the meaningful business error message.
Expected Output
Total must be positive
Important Behavior and Edge Cases
Avoid raising plain strings or generic exceptions when ValueError or TypeError describes the problem more precisely.
Try It Yourself
Write a function that raises ValueError for a negative quantity.
Common Beginner Mistakes
- Avoid raising plain strings or generic exceptions when ValueError or TypeError describes the problem more precisely.
- 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 deliberately signals an error when input violates an operation’s contract.
- The invalid denominator is rejected before any division occurs.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.