Lesson 31 / 49
Raising & Custom Exceptions
Raise exceptions to reject bad input early, and define custom exception classes for your domain.
raise
raise triggers an exception manually — useful for rejecting invalid input as early as possible.
def set_age(age):
if age < 0:
raise ValueError("age can't be negative")
return age
set_age(-5) # raises ValueError: age can't be negativeCustom exception class
Subclass Exception to create a domain-specific error your code — and callers — can catch by name.
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("not enough balance")
return balance - amount
try:
withdraw(100, 500)
except InsufficientFundsError as e:
print("Blocked:", e)