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.")| Exception | Happens when |
|---|---|
ValueError | Wrong value, e.g. int("abc") |
TypeError | Wrong type, e.g. "5" + 1 |
KeyError | Missing dictionary key |
IndexError | List index out of range |
FileNotFoundError | File doesn't exist |
ZeroDivisionError | Dividing by zero |
Raising your own
def withdraw(balance, amount):
if amount > balance:
raise ValueError("Not enough balance")
return balance - amount