capypad
0 day streak
python / intermediate
Snippet

Creating Custom Exceptions

Defining custom exceptions makes your error handling more specific and readable. It allows users of your code to catch particular errors rather than generic ones.

snippet.py
python
1
2
3
4
5
6
7
class ValidationError(Exception):
"""Raised when input data is invalid."""
pass
 
def check_age(age):
if age < 0:
raise ValidationError("Age cannot be negative")
Breakdown
1
class ValidationError(Exception):
Creates a new exception type by inheriting from the built-in Exception class.
2
raise ValidationError(...)
Manually triggers the custom exception when a specific condition is met.