Loading

Quipoin Menu

Learn • Practice • Grow

python / Custom Exceptions
tutorial

Custom Exceptions

Sometimes you need to define your own exception classes to represent errors specific to your application. Custom exceptions make code more readable and help distinguish error types. You can create a custom exception by subclassing the built‑in `Exception` class (or any of its subclasses).

Defining a Custom Exception
Create a class that inherits from `Exception`. You can add custom attributes or methods, but often a simple class suffices.


class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Insufficient funds: balance {balance}, attempted withdrawal {amount}")

Using a Custom Exception
Raise and catch it like built‑in exceptions.


def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount

try:
new_balance = withdraw(100, 150)
except InsufficientFundsError as e:
print(e) # Insufficient funds: balance 100, attempted withdrawal 150

Best Practices
  • Name custom exceptions with an "Error" suffix.
  • Provide meaningful error messages, possibly include relevant data.
  • Inherit from `Exception` directly, not `BaseException`.
  • Use custom exceptions to separate domain‑specific errors from system errors.
Two Minute Drill
  • Custom exceptions are subclasses of `Exception`.
  • They make error handling more expressive.
  • You can add custom attributes and pass meaningful messages.
  • Raise and catch them like any other exception.
  • Use them for domain‑specific error conditions.

Need more clarification?

Drop us an email at career@quipoinfotech.com