Codzy

Creating your own exceptions

You can create your own error types by writing a class that inherits from Exception: class InsufficientFunds(Exception):. The error's name explains the problem straight away.

The raise keyword triggers an exception, with a message in parentheses. Elsewhere in the program, you catch it with try / except, just like Python's own errors.

class InsufficientFunds(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFunds("Not enough money")
    return balance - amount

try:
    withdraw(20, 50)
except InsufficientFunds as e:
    print("Refused:", e)

Start the lesson