Custom Exceptions Python: Create and Handle Them

To handle an application-specific failure separately in Python, define a custom exception for it. A custom exception is a named error type that code can raise and callers can catch.

This article shows how to define and raise a custom exception, then choose the message callers see.

TL;DR

A custom exception is a named Exception subclass for a failure callers need to handle separately.

  • Subclass Exception, not BaseException.
  • Raise it at the failure point and catch its class or parent.
  • Store context in attributes and pass the display message to super().__init__().

What Is a Custom Exception in Python?

An exception reports a condition a function cannot complete. ValueError signals an unacceptable value, and KeyError signals a missing mapping key.

Use a custom class when callers need a distinct response to an application-specific failure.

Return None when absence is an ordinary result. Raise when the operation should stop so a caller can recover.

Exception typeSignalsTypical response
ValueErrorA value is outside the accepted set or rangeCorrect the supplied value
KeyErrorA requested mapping key is absentUse a fallback or report the missing key
TypeErrorAn operation receives a value of the wrong typeConvert or reject the input
Custom domain classAn application-specific conditionChoose an action for that domain event

How to Create Custom Exceptions in Python Step by Step

Define a domain exception near the code that detects the failure, then catch it where a response is possible.

Step 1: Define the error and raise it at the failure point

The lookup returns A17’s stock count or raises UnknownSKUError when the key is absent.

An uncaught error propagates to the caller. A matching handler can inspect its type and fields, recover, or re-raise it.

class CatalogError(Exception):
    def __init__(self, sku, message):
        self.sku = sku
        super().__init__(message)


class UnknownSKUError(CatalogError):
    pass


def stock_for(sku):
    inventory = {"A17": 5}
    if sku not in inventory:
        raise UnknownSKUError(sku, f"Unknown SKU: {sku}")
    return inventory[sku]


print(f"A17 stock: {stock_for('A17')}")
try:
    stock_for("Z9")
except CatalogError as error:
    print(f"{type(error).__name__}: {error} [sku={error.sku}]")
    print(f"message args: {error.args!r}")

Output:

vijaykrishna@askpython:~$ python3 custom_exception_path.py
A17 stock: 5
UnknownSKUError: Unknown SKU: Z9 [sku=Z9]
message args: ('Unknown SKU: Z9',)
Terminal output shows a custom UnknownSKUError and its SKU field
The command returns a stock count, then prints the named error and SKU.

I ran the command. A17 returned stock 5, and the CatalogError handler reported Z9’s SKU and message arguments.

CatalogError lets callers catch inventory failures together. Use the child class when a missing SKU needs a different response.

Step 2: Choose the message that callers should see

The initializer controls the contents of args and the default string representation.

class RawPayloadError(Exception):
    def __init__(self, code, message):
        self.code = code
        self.message = message


class MessageError(Exception):
    def __init__(self, code, message):
        self.code = code
        self.message = message
        super().__init__(message)


raw = RawPayloadError("E42", "record absent")
normalized = MessageError("E42", "record absent")
print(f"without super: args={raw.args!r}; str={str(raw)!r}")
print(f"with super: args={normalized.args!r}; str={str(normalized)!r}")

Output:

vijaykrishna@askpython:~$ python3 exception_args_probe.py
without super: args=('E42', 'record absent'); str="('E42', 'record absent')"
with super: args=('record absent',); str='record absent'
Terminal output compares exception arguments and string messages
The output compares the default string with a message passed to the base initializer.

I ran both initializers and saw two args when the base was skipped, versus one message arg and that message as str(error) after calling super().

Overriding __init__ changes args, which can affect callers that unpack it. Use named attributes for stable fields, or inherit the initializer for a message-only exception.

Exception text can appear in logs, so exclude credentials or private input.

Edge Cases When Raising Custom Exceptions

Document the exception types each public function may raise.

I first raised a plain class. Python raised a TypeError before the handler ran.

class InvalidEntry:
    pass


try:
    raise InvalidEntry()
except TypeError as error:
    print(f"{type(error).__name__}: {error}")

Output:

vijaykrishna@askpython:~$ python3 invalid_exception_base.py
TypeError: exceptions must derive from BaseException
Terminal output shows the TypeError from raising a class that does not inherit from BaseException
The terminal displays the exception message after the command.

I ran this command and got “TypeError: exceptions must derive from BaseException.” Deriving from Exception fixed it.

CaseSymptomFix
Multiple built-in exception basesBase classes may conflict over args or memory layoutChoose one exception base
Child handler after parentThe parent catches the child firstPut the specific except first
Initializer printsConstruction emits output before handlingStore fields, let callers choose logging or display

Let undocumented failures propagate. Log or convert them at a higher boundary that can respond.

Do not turn programming errors into successful returns. When translating a lower-level failure, exception chaining preserves its cause. Python’s section 8.5 covers explicit causes such as OSError or KeyError.

Names often end in Error, though Python does not enforce that convention. Name the failed operation or resource.

Conclusion

For exception hierarchies and causes, read sections 8.5–8.6 of Python’s errors and exceptions tutorial and its built-in exception reference. AskPython’s Exception Handling in Python article covers try/except, while its Python class constructor article covers __init__.

FAQ

Common choices when adding a custom exception:

Can you pass parameters to a custom exception in Python?

Yes. Define initializer parameters, store needed values as attributes, and pass the display message to super().__init__(). Those values become args.

How do you catch a custom exception in Python?

Catch its class to inspect fields. A shared parent catches child classes, so put specific handlers first.

Should a custom exception inherit from BaseException?

Use Exception or its subclass for application errors. BaseException also covers KeyboardInterrupt and SystemExit, which ordinary handlers should let escape.

Vijaykrishna Ram
Vijaykrishna Ram
Articles: 99