Lesson 30 / 47

Raising & Custom Exceptions

Signal errors on purpose, and define your own exception types.

raise

raise triggers an exception manually — useful for rejecting invalid input as early as possible.

def set_age(age):
    if age < 0:
        raise ValueError("age can't be negative")
    return age

set_age(-5)   # raises ValueError: age can't be negative

Custom exception class

Subclass Exception to create a domain-specific error your code — and callers — can catch by name.

class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("not enough balance")
    return balance - amount

try:
    withdraw(100, 500)
except InsufficientFundsError as e:
    print("Blocked:", e)