Thuta Learning
Python
IntermediateProgrammingBeginner

Custom Exceptions (Enhanced)

PythonLesson 2730 min

What you'll walk away with

  • Describe BaseException, Exception and the built-in families such as ArithmeticError, LookupError and OSError
  • Raise the right built-in exception with raise
  • Build custom exception classes with attributes under one app-wide base exception
  • Link a cause with raise ... from ... and re-raise with a bare raise without losing the traceback

Explain it simply

Explain it simply

Think of a hospital emergency room. If a patient only says "I feel bad", nobody knows which department should take them. Saying "my leg is broken" sends them straight to orthopaedics. Exceptions work the same way: the kind of error, its class, decides who handles it.

Departments are grouped in levels too: surgery contains orthopaedics and cardiology, just as Python's LookupError contains KeyError and IndexError. For your own application you can build precisely named exception classes such as InsufficientFundsError and throw them with raise.

Problem → Why → Solution

The problem: a generic Exception and guessing from its message

withdraw() raises a plain Exception when the money is not enough. The caller wants to catch only this error, but its only option is except Exception:, which also catches typos and bugs. Then it guesses by checking whether the message contains the word "balance". The day someone rewords the message to "Insufficient funds", the caller's logic silently breaks.

generic_exception.py
def withdraw(balance, amount):
    if amount > balance:
        raise Exception("Not enough balance")    # no specific type
    return balance - amount

try:
    withdraw(100, 500)
except Exception as e:                           # catches bugs too
    if "balance" in str(e):                      # guessing from the text
        print("ask the user for a smaller amount")

Why is this design poor?

except clauses select by an exception's class, never by its message text. If each kind of error has no class of its own, callers cannot catch it precisely. Define class InsufficientFundsError(Exception) and raise that instead: the caller writes except InsufficientFundsError:, rewording the message breaks nothing, and the exception can carry data such as the shortfall as an attribute.

Core concept: exceptions form a class hierarchy

Every Python exception is a class that ultimately inherits from BaseException. except SomeError: catches SomeError and all of its subclasses, following the same inheritance and isinstance() rules as the earlier lessons. That is why except LookupError: catches both KeyError and IndexError.

text
Part of Python's built-in exception hierarchy
---------------------------------------------
BaseException
 +-- SystemExit            (sys.exit())
 +-- KeyboardInterrupt     (Ctrl+C)
 +-- Exception             <- your own exceptions inherit from here
      +-- ArithmeticError
      |    +-- ZeroDivisionError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- OSError
      |    +-- FileNotFoundError
      +-- TypeError
      +-- ValueError

SystemExit and KeyboardInterrupt are direct children of BaseException, not of Exception, so except Exception: does not swallow requests to stop the program. Always derive your own exceptions from Exception or one of its subclasses, never directly from BaseException.

An exception object is an ordinary instance: e.args holds the arguments given to the constructor, str(e) gives the message, and e.__traceback__ records where it was raised. Once raised, it unwinds the call stack frame by frame until a matching except is found, so a function deep inside the code can report a problem to a caller many levels up without every function in between checking return codes.

The raise statement throws an exception: raise ValueError("age must be positive"). When a built-in type fits, use it: TypeError for the wrong type, ValueError for the right type with a bad value. For your application's business rules, such as insufficient funds or an order that is already closed, define a custom exception class. A custom exception is an ordinary class: write class AppError(Exception): and add your own __init__ and attributes, but call super().__init__(message) so str(e) shows the message.

With one base class such as AppError for the whole application and ValidationError, InsufficientFundsError and the rest underneath it, callers can catch one specific kind or every app error at once with except AppError:. Do not use exceptions for routine branching that an if/else expresses well; keep them for validation boundaries, I/O and genuinely exceptional situations.

Mental model: from raise to the matching except
  1. raise SomeError(...) builds an object
  2. It climbs the call stack frame by frame
  3. First except that isinstance-matches wins
  4. Nobody catches it: traceback, exit

except Parent: catches every subclass of Parent, which is why the hierarchy design matters.

General pattern

python
class AppError(Exception):
    """Base for all errors this app raises."""

class SpecificError(AppError):
    def __init__(self, detail):
        super().__init__(f"readable message about {detail}")
        self.detail = detail

raise SpecificError(value)                # throw it
raise SpecificError(value) from original  # keep the cause
raise                                     # inside except: re-raise as is

Keep one app-wide base class and make each kind of error a subclass. super().__init__() stores the message, and your own attributes carry data for the caller. The deeper sections below cover the three forms of raise in detail.

Example: custom exceptions for a bank withdrawal

ValidationError and InsufficientFundsError are built under an AppError base class, and withdraw() raises whichever fits. The caller handles ValidationError on its own and catches every other app error with except AppError. The last line prints the inheritance chain of the built-in ZeroDivisionError.

bank_errors.py
class AppError(Exception):
    """Base class for every error this app raises on purpose."""


class ValidationError(AppError):
    def __init__(self, field, message):
        super().__init__(f"{field}: {message}")   # sets str(e)
        self.field = field


class InsufficientFundsError(AppError):
    def __init__(self, balance, amount):
        super().__init__(f"need {amount}, have {balance}")
        self.shortfall = amount - balance


def withdraw(balance, amount):
    if amount <= 0:
        raise ValidationError("amount", "must be positive")
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount


for amount in [30, -5, 500]:
    try:
        print("new balance:", withdraw(100, amount))
    except ValidationError as e:
        print(f"bad field {e.field!r} -> {e}")
    except AppError as e:                  # any other app error
        print(f"{type(e).__name__}: {e}")

print(issubclass(InsufficientFundsError, AppError))
print([cls.__name__ for cls in ZeroDivisionError.__mro__])

Code breakdown

  1. Line 1class AppError(Exception):

    The base class for all of the application's errors. Its body is only a docstring, which is enough to make a valid class.

  2. Line 7super().__init__(f"{field}: {message}") # sets str(e)

    Passing the message to Exception.__init__ makes str(e) return "amount: must be positive". Without this line, str(e) would fall back to the raw constructor arguments, ('amount', 'must be positive'), instead of a readable message.

  3. Line 14self.shortfall = amount - balance

    An exception is an object too, so it can carry data for the caller as attributes; nobody has to parse the message text.

  4. Line 21raise InsufficientFundsError(balance, amount)

    raise creates the exception object and throws it. The rest of withdraw() does not run; control jumps straight to the caller's try.

  5. Line 30except AppError as e: # any other app error

    InsufficientFundsError is a subclass of AppError, so this clause catches it. ValidationError was already caught by the clause above.

  6. Line 34print([cls.__name__ for cls in ZeroDivisionError.__mro__])

    Shows that built-in exceptions live in the same kind of hierarchy: ZeroDivisionError, ArithmeticError, Exception, BaseException, object.

You should see
new balance: 70
bad field 'amount' -> amount: must be positive
InsufficientFundsError: need 500, have 100
True
['ZeroDivisionError', 'ArithmeticError', 'Exception', 'BaseException', 'object']
Error Handling Visual Guide
The try/except flow as a reference visual for the custom-exceptions lesson.

Exception chaining with raise ... from ...

When you catch a low-level error such as KeyError or ValueError and want to turn it into a domain error the caller understands, such as ConfigError, write raise NewError(...) from original. The original exception is kept in e.__cause__, and the traceback shows both with "The above exception was the direct cause of the following exception". You add context without losing any debugging information.

chaining.py
class ConfigError(Exception):
    pass

def read_port(settings):
    try:
        return int(settings["port"])
    except (KeyError, ValueError) as e:
        raise ConfigError("port must be a whole number") from e

try:
    read_port({"port": "eighty"})
except ConfigError as e:
    print("ConfigError:", e)
    print("caused by:", repr(e.__cause__))

Re-raising with a bare raise

When an except block should do something, such as writing a log line, and then let the error continue, write raise with no argument. It re-throws the very exception being handled, with its original traceback. raise e also works, but it adds this line to the traceback, so the bare form reads more cleanly.

reraise.py
def save(record):
    raise PermissionError("database is read-only")

def save_with_log(record):
    try:
        save(record)
    except PermissionError:
        print("log: save failed for", record)
        raise                     # same exception, original traceback

try:
    save_with_log({"id": 7})
except PermissionError as e:
    print("caller saw:", e)

In real projects

Where this shows up in real projects

Every well-designed library has its own exception hierarchy. In requests, RequestException sits above ConnectionError, Timeout, HTTPError and others, so users can retry only on timeouts or handle every network problem at once with except RequestException:. In Django, exceptions such as ObjectDoesNotExist, ValidationError and PermissionDenied are turned into HTTP 404, 400 and 403 responses by the framework.

In your own services, exceptions such as PaymentError(AppError) carry a stable code like "card_declined" and a user-safe message as attributes. The API layer catches them with except AppError as e: and puts e.code into the JSON response. Because the database driver's error was converted with raise PaymentError(...) from e, users never see internal details, while developers still see the full original cause in the logs.

Common mistakes

Common mistakes

1. Inheriting from BaseException

class MyError(BaseException): escapes except Exception:, slips past top-level error handlers and can bring the whole program down. BaseException is for interpreter-level signals such as SystemExit and KeyboardInterrupt; derive your own exceptions from Exception.

2. Forgetting super().__init__() in a custom __init__

If __init__ only sets self.field = field and never calls super().__init__(message), str(e) shows the raw constructor arguments instead of the message you meant: ValidationError("amount", "must be positive") prints as a tuple, ('amount', 'must be positive'). If the arguments were passed by keyword, str(e) is even an empty string and the log gives no hint of what went wrong. Always pass the message to the parent.

3. Translating an error and losing its cause

except KeyError: raise ConfigError("bad config") from None hides the original KeyError from the traceback. Use from None only when you truly need a clean message, for example in a CLI, and normally link the cause with from e.

Mini challenge

Mini challenge: an exception hierarchy for a config loader

Write load_config(), which validates a config dictionary. Each kind of problem needs its own exception class under a ConfigError base.

  • Build MissingKeyError and InvalidValueError under a ConfigError(Exception) base, both with a key attribute
  • Raise MissingKeyError when "host" or "port" is missing
  • When int() cannot convert the port, raise InvalidValueError from e
  • Also raise InvalidValueError when the port is outside 1-65535
config_loader.py
class ConfigError(Exception):
    """Base class for configuration problems."""


class MissingKeyError(ConfigError):
    def __init__(self, key):
        # TODO: pass a readable message to the parent and keep self.key
        pass


# TODO: InvalidValueError(ConfigError) taking key and value


def load_config(raw):
    # TODO: raise MissingKeyError for a missing "host" or "port"
    # TODO: convert the port with int(); on ValueError raise ... from e
    # TODO: reject ports outside 1..65535
    # TODO: return {"host": ..., "port": ...}
    pass


# TODO: try four samples (valid, missing port, "http", "70000") and print
#       "ok:", "missing:" or "invalid:" for each, including the cause type

Expected: Expected output: ok: {'host': 'localhost', 'port': 8080} missing: port invalid: 'port' has invalid value 'http' (cause: ValueError) invalid: 'port' has invalid value 70000 (cause: none)

Show hint

e.__cause__ holds the original exception when you used from, and None otherwise. Put except MissingKeyError before except ConfigError, because it is the subclass.

Show solution
config_loader.py
class ConfigError(Exception):
    """Base class for configuration problems."""


class MissingKeyError(ConfigError):
    def __init__(self, key):
        super().__init__(f"missing required key {key!r}")
        self.key = key


class InvalidValueError(ConfigError):
    def __init__(self, key, value):
        super().__init__(f"{key!r} has invalid value {value!r}")
        self.key = key


def load_config(raw):
    for key in ("host", "port"):
        if key not in raw:
            raise MissingKeyError(key)
    try:
        port = int(raw["port"])
    except ValueError as e:
        raise InvalidValueError("port", raw["port"]) from e
    if not 1 <= port <= 65535:
        raise InvalidValueError("port", port)
    return {"host": raw["host"], "port": port}


samples = [
    {"host": "localhost", "port": "8080"},
    {"host": "localhost"},
    {"host": "localhost", "port": "http"},
    {"host": "localhost", "port": "70000"},
]
for raw in samples:
    try:
        print("ok:", load_config(raw))
    except MissingKeyError as e:
        print("missing:", e.key)
    except ConfigError as e:
        cause = type(e.__cause__).__name__ if e.__cause__ else "none"
        print(f"invalid: {e} (cause: {cause})")

Quick quiz 1 / 3

What does this print? try: [1, 2][5] / except LookupError: print("L") / except IndexError: print("I")

Quick quiz 2 / 3

Given class MyError(Exception): def __init__(self, field, reason): self.field = field (no super() call), what does print(str(MyError("age", "negative"))) show?

Quick quiz 3 / 3

Inside except ValueError as e:, you want to raise ConfigError and keep the original ValueError for debugging. Which do you write?

What to remember

  • Every exception is a class under BaseException, and except Parent: catches all of its subclasses.
  • Raise ValueError or TypeError when a built-in fits; create custom exceptions for business rules.
  • Derive custom exceptions from Exception under one app-wide base and call super().__init__(message).
  • raise ... from e links the cause, and a bare raise re-throws the caught exception with its traceback intact.

Python Documentation — Errors and Exceptions — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Custom Exceptions (Enhanced) | Thuta Learning