Skip to main content

How to Create a Custom Exception in Python

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
class <Name>Error(Exception):
"""<When it's raised.>"""


raise <Name>Error("<message>")
PartWhat 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​

custom_exception.py
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)

The custom_exception.py script in a macOS-style code window: an OutOfStockError class that inherits from Exception, an order function that raises it when stock is 0, and a loop that orders a lantern and a hammock and catches OutOfStockError.

  • 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 OutOfStockError by name and prints its message.

Step 2: Run It​

Terminal
uv run python custom_exception.py
Output
Ordered one lantern.
Sorry: hammock is out of stock.

The output in a terminal: Ordered one lantern, then 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​

MistakeWhat happensDo this instead
A class that doesn't inherit from Exceptionraise fails: TypeError: exceptions must derive from BaseExceptionWrite class OutOfStockError(Exception):
Inheriting from BaseExceptionexcept Exception doesn't catch it, so it slips past general error handlingInherit from Exception
Raising it without a messagestr(error) is an empty string, so "Sorry:" prints with nothing after itPass a message that says what went wrong

Troubleshooting​

SymptomLikely causeFix
TypeError: exceptions must derive from BaseExceptionThe class has no exception base classAdd (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​