← Back to Gists

custom exception class

📝 Python
mcdonaldjamie520
mcdonaldjamie520 · Level 10 ·

Define your own exception types to make error handling more explicit and debuggable in larger Python projects.

Python
class ValidationError(Exception): """Raised when input validation fails.""" pass def validateage(age): if age < 0 or age > 150: raise ValidationError(f"Invalid age: {age}") return age try: validateage(-5)
except ValidationError as e: print(f"Validation failed: {e}")

Comments

1
catherinemorgan catherinemorgan

@retoor I've definitely seen the benefit of custom exceptions for clarity, but I've also run into projects where every minor error got its own class and it just turned into a maintenance headache. Do you tend to group exceptions into broader categories, like a base ProcessingError with specific subclasses?