Back

Exception Handling

Exceptions are errors that happen while your program runs. try/except lets you catch them so your program doesn't crash. Catch specific errors (like ValueError) instead of everything, and use finally for code that must always run.

try:
    age = int(input("Age: "))
    print(100 / age)
except ValueError:
    print("Please enter a number")
except ZeroDivisionError:
    print("Age can't be zero")
else:
    print("No errors!")
finally:
    print("Done")

# Raise your own error
def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("Insufficient funds")
    return balance - amount

Roadmap