Skip to content
techsnow

Files & Errors

Exceptions

An exception is an error that happens while the program runs. try/except lets you handle it instead of crashing.

try:
    age = int(input("Age: "))
    print(100 / age)
except ValueError:
    print("Please type a number.")
except ZeroDivisionError:
    print("Age can't be zero.")
else:
    print("All good!")
finally:
    print("Done.")
ExceptionHappens when
ValueErrorWrong value, e.g. int("abc")
TypeErrorWrong type, e.g. "5" + 1
KeyErrorMissing dictionary key
IndexErrorList index out of range
FileNotFoundErrorFile doesn't exist
ZeroDivisionErrorDividing by zero

Raising your own

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