Custom Exceptions in Python
A custom exception is a new exception type defined for a specific program, created by subclassing Python's built-in Exception class (or a more specific existing exception). It lets code raise and catch errors that are meaningful to a particular application's domain, rather than making do with only generic built-in types.
Subclass Exception
Or a more specific, suitable built-in exception, whichever fits better.
A plain pass body is usually enough
Inheriting Exception's behavior covers most needs without extra code.
Add a custom __init__() if needed
For an exception that needs to carry extra data beyond a simple message.
Raise it like any built-in exception
raise MyCustomError("message") works exactly the same way.
Catch it the same way too
except MyCustomError as e behaves identically to catching a built-in type.
class InsufficientFundsError(Exception): pass def withdraw(balance, amount): if amount > balance: raise InsufficientFundsError(f"Cannot withdraw {amount}, balance is {balance}") return balance - amount try: withdraw(100, 150)except InsufficientFundsError as e: print(f"Transaction failed: {e}")Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.