0Pricing
Python Academy · Lesson

Custom Exception Classes

Define your own exception types for clearer error communication.

Custom Exception Classes is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

Custom exception classes make your error handling explicit, self-documenting, and easy for callers to handle precisely.

Why Custom Exceptions?

Built-in exceptions are too generic. Custom ones let callers catch only YOUR library's errors without catching unrelated ones.
class AppError(Exception):
    pass
raise AppError('something went wrong')

Inheriting from Exception

class MyError(Exception): pass is all you need. Always inherit from Exception, not BaseException.
class ValidationError(Exception):
    pass
try:
    raise ValidationError('email is invalid')
except ValidationError as e:
    print(e)

Adding Custom Attributes

class APIError(Exception): def __init__(self, status, message): self.status = status; super().__init__(message)
class APIError(Exception):
    def __init__(self, status, message):
        self.status = status
        super().__init__(message)
try:
    raise APIError(404, 'Not found')
except APIError as e:
    print(e.status, e)

Exception Hierarchy

Build a hierarchy: class DBError(AppError): pass — callers can catch AppError for any app error, or DBError specifically.
class AppError(Exception): pass
class DBError(AppError): pass
class NetworkError(AppError): pass
try:
    raise DBError('timeout')
except AppError as e:
    print('app error:', e)

Custom __str__ Method

Override __str__ to control how the exception message looks when printed.
class RangeError(ValueError):
    def __init__(self, val, lo, hi):
        self.val, self.lo, self.hi = val, lo, hi
    def __str__(self):
        return f'{self.val} not in [{self.lo}, {self.hi}]'
print(RangeError(15, 0, 10))

Raising Custom Exceptions

Use raise in your functions to signal domain-specific errors. This creates a clean API for callers.
class InsufficientFundsError(Exception):
    def __init__(self, needed, available):
        super().__init__(f'Need {needed}, have {available}')
def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(amount, balance)
    return balance - amount
try:
    withdraw(100, 200)
except InsufficientFundsError as e:
    print(e)

Catching by Base Class

except AppError catches all subclasses: DBError, NetworkError, etc. Hierarchy lets callers choose specificity.
class AppError(Exception): pass
class DBError(AppError): pass
try:
    raise DBError('conn failed')
except AppError:
    print('any app error')

Exception with Context Manager

Custom exceptions integrate with context managers: class suppressed: __exit__ returns True to suppress the exception.
class SuppressValue(Exception): pass
try:
    raise SuppressValue('ignored')
except SuppressValue:
    pass  # suppress silently
print('continued')

Documenting Custom Exceptions

Document WHEN to raise and WHAT the attributes mean. Good docstrings make custom exceptions usable.
class ConfigError(Exception):
    """Raised when configuration is invalid.
    Attributes:
        key: The invalid config key
    """
    def __init__(self, key, msg):
        super().__init__(msg)
        self.key = key

Best Practices

Keep hierarchy shallow (2-3 levels). Always inherit from Exception. Use descriptive names ending in Error. Place in a dedicated exceptions.py module.
# Good structure:
class AppError(Exception): pass
class ValidationError(AppError): pass
class NotFoundError(AppError): pass
print('hierarchy demo')

Quick Check

What should custom exceptions inherit from to avoid catching system-exiting events?

Recap

Custom exceptions: inherit from Exception, add attributes in __init__, override __str__. Build hierarchies for catchability. Place in exceptions.py module.

Keep Going

Great work! Move on to the next lesson to keep progressing.

Frequently asked questions

Is the “Custom Exception Classes” lesson free?

Yes — the full text of “Custom Exception Classes” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Custom Exception Classes”?

Define your own exception types for clearer error communication. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Custom Exception Classes” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Understanding Exceptions
  2. try / except / else / finally
  3. Raising and Re-raising Exceptions
  4. Custom Exception Classes
← Back to Python Academy