Syllabus Lesson 42 of 239 · Files, Errors & Modules
Files, Errors & Modules

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 age

For 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.

Your turn

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.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output