Skip to content

Module 12 · Exception Handling — topic 10 of 11

Custom exceptions

Defining your own exception classes: subclassing Exception, adding attributes, building an exception hierarchy for a project, and catching at the right level.

Beginner 10 min read·Lesson 192 of 306 in Python Programming

Learning objectives

  • Define custom exception classes
  • Add useful attributes to exceptions
  • Design a small exception hierarchy

Definition

A custom exception is a class that inherits from Exception (or one of its subclasses). It gives an application its own error types, which callers can catch precisely and which can carry extra data.

Introduction

ValueError says 'a value was wrong'. InsufficientFundsError says exactly what happened in a banking app. Custom exceptions make errors part of your program's vocabulary.

Why it matters

Callers can handle your domain errors specifically without accidentally catching unrelated built-in errors, and the exceptions can carry data such as the shortfall amount.

Detailed explanation

The simplest custom exception is class MyError(Exception): pass. The message is passed as usual: raise MyError('details').

Name exception classes with an Error suffix (Python's convention), unless the name already reads clearly as an error.

Add attributes by defining __init__, calling super().__init__(message) and storing extra data on self.

Create one base class per application or library (class BankError(Exception)) and derive specific errors from it. Callers can then catch everything from your code with one clause, or individual errors precisely.

Inherit from a built-in when the meaning fits: class InvalidAmountError(ValueError) is still caught by except ValueError.

Don't create a custom exception for every situation — use built-in ones when they describe the problem well.

Custom exceptions should be raised and documented as part of a function's interface, just like its return values.

Syntax

Python
class BankError(Exception):
"""Base class for banking errors."""
class InsufficientFunds(BankError):
def __init__(self, needed, available):
super().__init__(f"needed {needed}, available {available}")
self.shortfall = needed - available
  • Inherit from Exception.
  • Call super().__init__ with the message.
  • One base class per project.

Code examples

A simple custom exception

Python
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(f"need {amount - balance} more")
return balance - amount
try:
withdraw(100, 250)
except InsufficientFundsError as e:
print(type(e).__name__, "-", e)
Output
InsufficientFundsError - need 150 more

Carrying extra data

Python
class ValidationError(Exception):
def __init__(self, field, message):
super().__init__(f"{field}: {message}")
self.field = field
try:
raise ValidationError("email", "must contain @")
except ValidationError as e:
print(e, "| field =", e.field)
Output
email: must contain @ | field = email

More examples

An exception hierarchy for a bank

Python
class BankError(Exception):
"""Base class for all banking errors."""
class AccountNotFound(BankError):
def __init__(self, account_id):
super().__init__(f"no account {account_id}")
self.account_id = account_id
class InsufficientFunds(BankError):
def __init__(self, needed, available):
super().__init__(f"needed {needed}, available {available}")
self.shortfall = needed - available
accounts = {"A1": 500, "B2": 50}
def transfer(src, dst, amount):
for acc in (src, dst):
if acc not in accounts:
raise AccountNotFound(acc)
if accounts[src] < amount:
raise InsufficientFunds(amount, accounts[src])
accounts[src] -= amount
accounts[dst] += amount
return f"moved {amount} from {src} to {dst}"
for args in [("A1", "B2", 200), ("B2", "A1", 400), ("A1", "Z9", 10)]:
try:
print(transfer(*args))
except InsufficientFunds as e:
print("declined:", e, "| short by", e.shortfall)
except BankError as e:
print("bank error:", e)
print(accounts)
Output
moved 200 from A1 to B2
declined: needed 400, available 250 | short by 150
bank error: no account Z9
{'A1': 300, 'B2': 250}

Step-by-step explanation

  • All banking errors share the BankError base class.
  • The first handler deals specifically with insufficient funds and uses the shortfall attribute.
  • The second catches any other banking error; validation happens before any balance changes, so failed transfers leave accounts untouched.

Expected output

Running “An exception hierarchy for a bank” prints exactly:

TextOutput
moved 200 from A1 to B2
declined: needed 400, available 250 | short by 150
bank error: no account Z9
{'A1': 300, 'B2': 250}

Practical applications

  • requests.RequestException is the base of all requests errors.
  • Django's ValidationError carries field-specific messages.

Best practices

  • Give each project one base exception class.
  • Add attributes that help callers respond.
  • Reuse built-in exceptions when they fit.

Common mistakes

Inheriting from BaseException

Avoid

class MyError(BaseException): ...

Prefer

class MyError(Exception): ...

BaseException is reserved for system-exiting exceptions; except Exception wouldn't catch yours.

Forgetting super().__init__

Avoid

def __init__(self, field):
self.field = field

Prefer

def __init__(self, field):
super().__init__(f"invalid {field}")
self.field = field

Without it, str(e) is empty and the message is lost.

Important notes

  • Custom exceptions can also override __str__ for richer messages.

Key takeaways

  • Custom exceptions subclass Exception.
  • They can carry extra attributes.
  • A base class lets callers catch all project errors at once.

Try it yourself

  1. 1
    Create an InventoryError hierarchy with OutOfStock and UnknownProduct.
  2. 2
    Make a custom exception that inherits from ValueError and show it is caught by except ValueError.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic