Raising Errors
Use raise to stop with an error. Choose a fitting built-in type such as ValueError or TypeError, and give a clear message. You can also define your own error class by inheriting from Exception.
Example
class InsufficientFunds(Exception):
pass
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
if amount > balance:
raise InsufficientFunds(f"Only {balance} available")
return balance - amount
for amount in (50, -5, 500):
try:
print(withdraw(100, amount))
except (ValueError, InsufficientFunds) as error:
print(type(error).__name__, "-", error)Result
50 ValueError - Amount must be positive InsufficientFunds - Only 100 available
Exercise
Signal an error.
ValueError("bad value")Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.