Raising and Defining Exceptions
You can raise exceptions yourself with raise when something is wrong with the input. This is how good functions reject bad data loudly instead of returning a confusing result.
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return ageFor your own libraries it is often clearer to define a custom exception. You do that by subclassing the built-in Exception class. Even with no body it is fully usable:
class ValidationError(Exception):
pass
def register(name):
if not name:
raise ValidationError("name is required")
return name.upper()Callers can then catch your specific type:
try:
register("")
except ValidationError as e:
print(f"rejected: {e}")A custom type makes your errors self-documenting and lets callers handle your failures separately from built-in ones. Because it inherits from Exception, a broad except Exception still catches it too.
Define a custom exception class named InvalidScoreError that subclasses Exception. Then write a function validate_score(score) that raises InvalidScoreError if score is below 0 or above 100, and otherwise returns the score unchanged.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.