How to Create a Custom Exception in Python
Python's built-in errors describe Python's problems: a missing key, a wrong type. Your program has its own problems, like an item that's out of stock. A custom exception gives that problem a name, so the code that calls yours can catch exactly it. This guide creates one for a small order function, with real output from Python 3.15.2.
Syntax
class <Name>Error(Exception):
"""<When it's raised.>"""
raise <Name>Error("<message>")
| Part | What it means |
|---|---|
class <Name>Error(Exception): | A new exception type. It inherits everything from Exception |
"""<When it's raised.>""" | A docstring. It's enough for the class body: nothing else is needed |
raise <Name>Error("<message>") | Raises it, with a message for whoever catches it |
Python's tutorial: "Programs may name their own exceptions by creating a new exception class". It adds: "Exceptions should typically be derived from the Exception class, either directly or indirectly", and "Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions."
Prerequisites
- uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
class OutOfStockError(Exception):
"""Raised when an item can't be ordered because none are left."""
def order(item: str, stock: int) -> str:
if stock == 0:
raise OutOfStockError(f"{item} is out of stock.")
return f"Ordered one {item}."
for item, stock in [("lantern", 3), ("hammock", 0)]:
try:
print(order(item, stock))
except OutOfStockError as error:
print("Sorry:", error)

OutOfStockError(Exception)is the whole definition: the docstring says when it's raised.order()raises it with a message that names the item.- The loop catches
OutOfStockErrorby name and prints its message.
Step 2: Run It
uv run python custom_exception.py
Ordered one lantern.
Sorry: hammock is out of stock.

The lantern was in stock, so order() returned normally. The hammock wasn't, so order() raised OutOfStockError, and the except caught it: print(error) shows the message given to raise.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
A class that doesn't inherit from Exception | raise fails: TypeError: exceptions must derive from BaseException | Write class OutOfStockError(Exception): |
Inheriting from BaseException | except Exception doesn't catch it, so it slips past general error handling | Inherit from Exception |
| Raising it without a message | str(error) is an empty string, so "Sorry:" prints with nothing after it | Pass a message that says what went wrong |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
TypeError: exceptions must derive from BaseException | The class has no exception base class | Add (Exception) after its name |
FAQ
Does the class need an __init__?
No. Exception already stores the message you pass to it, which is what print(error) shows.
Should I catch it or let it propagate?
Catch it where you can do something useful, as the loop does by apologising and moving on. Elsewhere, let it carry on to code that can.
Conclusion
class OutOfStockError(Exception) gave the out-of-stock case its own name. order() raised it for the hammock, and except OutOfStockError caught exactly that error and printed its message.
Additional Resources
- User-defined Exceptions — defining your own exception classes.
- Exception hierarchy — where
ExceptionandBaseExceptionsit.
