Custom Exceptions
Python provides many built-in exceptions like ValueError, TypeError, and FileNotFoundError. But what if your application needs a very specific error type that Python does not have?
For example, in a banking app, you might want an InsufficientBalanceError. Python does not have this — so you create it yourself.
How to Create a Custom Exception
A custom exception is simply a Python class that inherits from the built-in Exception class:
class InsufficientBalanceError(Exception):
pass
That is it! Now you can raise it just like any built-in exception:
class InsufficientBalanceError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError(
f"Cannot withdraw ₹{amount}. Available balance: ₹{balance}"
)
return balance - amount
try:
remaining = withdraw(500, 1000)
except InsufficientBalanceError as e:
print("Transaction denied:", e)
# Output: Transaction denied: Cannot withdraw ₹1000. Available balance: ₹500
When to Use Custom Exceptions
Use custom exceptions when:
- Built-in exceptions are too generic for your use case
- You want the caller to handle your specific error differently from general errors
- You are building a library or API that other developers will use
For most beginner projects, built-in exceptions like ValueError are sufficient. Create custom exceptions only when your application genuinely needs a distinct error type.
Quick Summary
- Custom Exception Creation: Inherit from Python's base
Exceptionclass:class CustomError(Exception): pass. - Domain Modeling: Custom exceptions make application code expressive and allow callers to handle domain failures specifically (e.g.,
InvalidAuthTokenError). - Attributes & Messages: Custom exception classes can accept and store extra contextual details like error codes or user IDs.
What's Next?
Congratulations on mastering error handling! Next up is Module 15: File Handling, where you will learn how to read and write permanent files on disk!