How to raise an exception


As you create more and more complex applications you'll reach a point where you write a function, probably in a module, that needs to report some error condition. You can raise an exception in a simple way.

examples/exceptions/raise.py
def add_material(name, amount):
    if amount <= 0:
        raise Exception(f"Amount of {name} must be positive. {amount} was given.")
    print(f"Adding {name}: {amount}")

def main():
    things_to_add = (
        ("apple", 3),
        ("sugar", -1),
        ("banana", 2),
    )

    for name, amount in things_to_add:
        try:
            add_material(name, amount)
        except Exception as err:
            print(f"Exception: {err}")
            print("Type: " + type(err).__name__)

main()

$ python raise.py 
Adding apple: 3
Exception: Amount of sugar must be positive. -1 was given.
Type: Exception
Adding banana: 2