Skip to content
Python

Python raise and Custom Exceptions

Ihsan Ullah · 16 min read
Python Custom Exceptions, Lesson 36 of the Python course: raise, re-raise and your own exception classes

Python course · Module 7: Files and errors · Lesson 36 of 63

Quick answer: Use raise to stop a function and report a problem: raise ValueError("quantity must be at least 1"). To make a Python custom exception, write a small class that inherits from Exception, for example class OutOfStockError(Exception): pass, and raise it like any built-in error. Inside an except block, a bare raise sends the same error on, and raise NewError(...) from err raises a new error and keeps the old one as its cause.

In this lesson you will learn:

  • how to raise a built-in exception with a clear message
  • how to re-raise an error with a bare raise
  • how raise ... from chains exceptions, and what __cause__ and __context__ mean
  • how to define your own exception classes, a small hierarchy and extra attributes
  • when to raise an error and when to return None, plus add_note()

Before you start: finish Lesson 35, Python try, except, else and finally: Handle Errors. You need functions from Lesson 22 and dictionaries from Lesson 17. All examples were run on Linux with Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org.

Raise an exception with raise

In Lesson 35 you caught errors that Python raised. Your own functions can raise errors too. Our running example is a small shop. A function checks the quantity a customer orders:

def check_quantity(quantity):
    if quantity <= 0:
        raise ValueError(f"quantity must be at least 1, got {quantity}")
    return quantity


print(check_quantity(3))
print(check_quantity(-2))
print("This line never runs")
3
Traceback (most recent call last):
  File "/home/learner/python-course/w36/step1_raise.py", line 8, in <module>
    print(check_quantity(-2))
          ~~~~~~~~~~~~~~^^^^
  File "/home/learner/python-course/w36/step1_raise.py", line 3, in check_quantity
    raise ValueError(f"quantity must be at least 1, got {quantity}")
ValueError: quantity must be at least 1, got -2
  • raise stops the function at once. Nothing after it runs, and the function returns no value.
  • ValueError(...) creates an exception object. The text inside becomes the message on the last line of the traceback.
  • No except caught the error, so the program stopped, and the last print() never ran.

Write the message for the person who will read it. “quantity must be at least 1, got -2” says what is wrong and which value caused it.

Which built-in exception should you raise?

Pick the built-in exception whose meaning fits. The built-in exceptions page says ValueError is for an argument that “has the right type but an inappropriate value”, and TypeError is for an object “of inappropriate type”. A quantity of -2 is the right type with a wrong value. A quantity of "5" (a string) is the wrong type:

def check_quantity(quantity):
    if not isinstance(quantity, int):
        raise TypeError(f"quantity must be an int, got {type(quantity).__name__}")
    if quantity <= 0:
        raise ValueError(f"quantity must be at least 1, got {quantity}")
    return quantity


for value in [3, -2, "5"]:
    try:
        print("OK:", check_quantity(value))
    except (ValueError, TypeError) as err:
        print(f"{type(err).__name__}: {err}")
OK: 3
ValueError: quantity must be at least 1, got -2
TypeError: quantity must be an int, got str

isinstance(), which you met in Lesson 26, checks the type first. The caller catches your errors exactly like Python’s own errors, and type(err).__name__ gives the class name of the error.

You can also write raise ValueError without parentheses. The Python tutorial calls this a “shorthand for ‘raise ValueError()'”. It has no message, so always prefer a message:

try:
    raise ValueError
except ValueError as err:
    print(repr(err))
    print("Message:", repr(str(err)))
ValueError()
Message: ''

Re-raise an error with a bare raise

Sometimes you want to notice an error, do something small, and still let it go up to the caller. Inside an except block, raise on its own raises the same error again:

def read_quantity(text):
    try:
        return int(text)
    except ValueError:
        print(f"Could not read a quantity from {text!r}")
        raise


print(read_quantity("4"))
print(read_quantity("ten"))
4
Could not read a quantity from 'ten'
Traceback (most recent call last):
  File "/home/learner/python-course/w36/step4_reraise.py", line 10, in <module>
    print(read_quantity("ten"))
          ~~~~~~~~~~~~~^^^^^^^
  File "/home/learner/python-course/w36/step4_reraise.py", line 3, in read_quantity
    return int(text)
ValueError: invalid literal for int() with base 10: 'ten'

Our message was printed, and then the original ValueError from int() (Lesson 8) continued with its full traceback. A bare raise keeps the real error. That is better than raising a new, vaguer one.

Exception chaining with raise … from

Often you catch a low-level error and raise a clearer one for your own code. Here a missing dictionary key becomes a ValueError:

prices = {"pen": 1.5, "notebook": 3.0}


def get_price(item):
    try:
        return prices[item]
    except KeyError:
        raise ValueError(f"we do not sell {item!r}")


print(get_price("pencil"))
Traceback (most recent call last):
  File "/home/learner/python-course/w36/step5_context.py", line 6, in get_price
    return prices[item]
           ~~~~~~^^^^^^
KeyError: 'pencil'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/learner/python-course/w36/step5_context.py", line 11, in <module>
    print(get_price("pencil"))
          ~~~~~~~~~^^^^^^^^^^
  File "/home/learner/python-course/w36/step5_context.py", line 8, in get_price
    raise ValueError(f"we do not sell {item!r}")
ValueError: we do not sell 'pencil'

Python shows both errors. “During handling of the above exception, another exception occurred” sounds like an accident: maybe the except block itself had a bug. To say “I raised this on purpose, because of that”, add from err:

    except KeyError as err:
        raise ValueError(f"we do not sell {item!r}") from err
Traceback (most recent call last):
  File "/home/learner/python-course/w36/step6_from.py", line 6, in get_price
    return prices[item]
           ~~~~~~^^^^^^
KeyError: 'pencil'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/learner/python-course/w36/step6_from.py", line 11, in <module>
    print(get_price("pencil"))
          ~~~~~~~~~^^^^^^^^^^
  File "/home/learner/python-course/w36/step6_from.py", line 8, in get_price
    raise ValueError(f"we do not sell {item!r}") from err
ValueError: we do not sell 'pencil'

Now the middle line says “direct cause”. The last line is always the newest error.

__cause__ vs __context__

Python stores the old error on the new one in two attributes. The exceptions docs explain: __context__ is set automatically when you raise inside except, and from sets __cause__. Setting __cause__ also sets __suppress_context__ to True. from None hides the old error from the traceback. This script tries all three forms. The chain argument only picks which raise line runs:

prices = {"pen": 1.5, "notebook": 3.0}


def get_price(item, chain):
    try:
        return prices[item]
    except KeyError as err:
        if chain == "no from":
            raise ValueError(f"we do not sell {item!r}")
        if chain == "from err":
            raise ValueError(f"we do not sell {item!r}") from err
        raise ValueError(f"we do not sell {item!r}") from None


for chain in ["no from", "from err", "from None"]:
    try:
        get_price("pencil", chain)
    except ValueError as err:
        print(f"{chain}: cause={err.__cause__!r}, context={err.__context__!r}, "
              f"suppress={err.__suppress_context__}")
no from: cause=None, context=KeyError('pencil'), suppress=False
from err: cause=KeyError('pencil'), context=KeyError('pencil'), suppress=True
from None: cause=None, context=KeyError('pencil'), suppress=True

With from None, the traceback shows only the new error, but the old one is still kept in __context__:

Traceback (most recent call last):
  File "/home/learner/python-course/w36/step8_from_none.py", line 11, in <module>
    print(get_price("pencil"))
          ~~~~~~~~~^^^^^^^^^^
  File "/home/learner/python-course/w36/step8_from_none.py", line 8, in get_price
    raise ValueError(f"we do not sell {item!r}") from None
ValueError: we do not sell 'pencil'

Use from err in most cases, because the old error helps you find the problem. Use from None only when the old error adds nothing for the reader.

Python custom exception classes

Built-in errors are general. A custom exception names a problem of your own program, so callers can catch exactly that problem. You make one with a class. Classes are taught properly in Lesson 38; for now you only need this shape:

class OutOfStockError(Exception):
    pass
  • class OutOfStockError creates a new type of error. By convention the name ends in Error, like the built-in ones.
  • (Exception) means “it is a kind of Exception“. The tutorial says exceptions “should typically be derived from the Exception class, either directly or indirectly”.
  • pass means “nothing more to add”. Everything else comes from Exception.
stock = {"pen": 10, "notebook": 2}


def buy(item, quantity):
    if quantity > stock[item]:
        raise OutOfStockError(f"only {stock[item]} {item} left, you asked for {quantity}")
    stock[item] -= quantity
    return stock[item]


print("Left:", buy("pen", 4))
print(issubclass(OutOfStockError, Exception))
buy("notebook", 5)
Left: 6
True
Traceback (most recent call last):
  File "/home/learner/python-course/w36/step9_custom.py", line 17, in <module>
    buy("notebook", 5)
    ~~~^^^^^^^^^^^^^^^
  File "/home/learner/python-course/w36/step9_custom.py", line 10, in buy
    raise OutOfStockError(f"only {stock[item]} {item} left, you asked for {quantity}")
OutOfStockError: only 2 notebook left, you asked for 5

issubclass(OutOfStockError, Exception) printed True: your class is a kind of Exception. The last line shows your own error name. Anyone reading it knows at once what went wrong.

A small exception hierarchy

Bigger programs give all their errors one base class. Then a caller can catch one specific error, or all errors of your program at once:

class ShopError(Exception):
    """Base class for all errors in our shop."""


class UnknownItemError(ShopError):
    """The shop does not sell this item."""


class OutOfStockError(ShopError):
    """Not enough items in stock."""

A docstring can replace pass as the class body. buy() now also raises UnknownItemError when the item is not in stock. We process three orders:

stock = {"pen": 10, "notebook": 2}


def buy(item, quantity):
    if item not in stock:
        raise UnknownItemError(f"we do not sell {item!r}")
    if quantity > stock[item]:
        raise OutOfStockError(f"only {stock[item]} {item} left, you asked for {quantity}")
    stock[item] -= quantity
    return stock[item]


orders = [("pen", 4), ("pencil", 1), ("notebook", 5)]
for item, quantity in orders:
    try:
        left = buy(item, quantity)
        print(f"Sold {quantity} {item}, {left} left")
    except OutOfStockError as err:
        print("Sorry:", err)
    except ShopError as err:
        print(f"Shop problem ({type(err).__name__}):", err)
Sold 4 pen, 6 left
Shop problem (UnknownItemError): we do not sell 'pencil'
Sorry: only 2 notebook left, you asked for 5
Python custom exception hierarchy from Lesson 36: ShopError inherits from Exception, and UnknownItemError and OutOfStockError inherit from ShopError, so one except ShopError catches both.
One base class for the whole shop: catch OutOfStockError on its own, or every shop error with except ShopError.

except ShopError catches UnknownItemError because it inherits from ShopError. Put the more specific except first: Python uses the first except that matches.

Extra attributes on a custom exception

A message is text. If the caller needs the numbers, store them on the error. This needs an __init__ method, which runs when the error is created (Lesson 38 explains __init__ and self in detail):

class OutOfStockError(ShopError):
    def __init__(self, item, wanted, available):
        super().__init__(f"only {available} {item} left, you asked for {wanted}")
        self.item = item
        self.wanted = wanted
        self.available = available
  • super().__init__(...) passes the message to Exception, so print(err) shows it.
  • self.item = item saves a value on the error object. The caller reads it as err.item.

In buy(), the raise line becomes raise OutOfStockError(item, quantity, stock[item]). The caller can now read the values:

try:
    buy("notebook", 5)
except OutOfStockError as err:
    print("Message:", err)
    print("Item:", err.item, "| wanted:", err.wanted, "| available:", err.available)
    print(f"Buy {err.available} instead? Left after that: {buy(err.item, err.available)}")
Message: only 2 notebook left, you asked for 5
Item: notebook | wanted: 5 | available: 2
Buy 2 instead? Left after that: 0

The caller used err.available to offer the 2 notebooks that are left, without parsing the message text.

Raise an error or return None?

A function that cannot do its job has two choices: return a special value such as None, or raise. Returning None is easy to miss:

def find_price(item):
    if item in prices:
        return prices[item]
    return None


print(find_price("pen"))
print(find_price("pencil"))
total = find_price("pencil") * 2
print("Total:", total)
1.5
None
Traceback (most recent call last):
  File "/home/learner/python-course/w36/step12_return_none.py", line 12, in <module>
    total = find_price("pencil") * 2
            ~~~~~~~~~~~~~~~~~~~~~^~~
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

The real problem (“we do not sell pencils”) became a confusing NoneType error on another line. A simple rule:

  • Raise when the caller asked for something wrong or impossible and should not continue as normal: bad input, a missing item they expected, a broken file.
  • Return None when “nothing found” is a normal, expected answer, and the caller will check for it, like dict.get() does.

Add a note to an error with add_note()

Since Python 3.11, every exception has add_note() (docs). It adds a line of extra information to an error you caught, and then you re-raise it:

order_lines = ["pen,2", "notebook,1", "ruler,two"]


def read_order(lines):
    order = {}
    for number, line in enumerate(lines, start=1):
        item, quantity = line.split(",")
        try:
            order[item] = int(quantity)
        except ValueError as err:
            err.add_note(f"while reading line {number} of the order: {line!r}")
            raise
    return order


read_order(order_lines)
Traceback (most recent call last):
  File "/home/learner/python-course/w36/step13_add_note.py", line 16, in <module>
    read_order(order_lines)
    ~~~~~~~~~~^^^^^^^^^^^^^
  File "/home/learner/python-course/w36/step13_add_note.py", line 9, in read_order
    order[item] = int(quantity)
                  ~~~^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'two'
while reading line 3 of the order: 'ruler,two'

enumerate() from Lesson 12 gives the line numbers. The note appears under the error message. The error type stays the same, so code that catches ValueError still works.

Try it yourself

Exercise 1: Check an age

Write set_age(age) that raises ValueError with a helpful message when age is below 0 or above 150, and returns the age otherwise. Test it with 25, -1 and 200 inside try/except.

Exercise 2: Password errors

Create PasswordError(Exception) and two subclasses, TooShortError and NoDigitError. Write check_password(password) that raises TooShortError for fewer than 8 characters and NoDigitError when there is no digit. Check "cat", "sunflower" and "sunflower7" and catch only PasswordError.

Exercise 3: Chain a KeyError

Create UnknownItemError(Exception). Change get_price() so a missing item raises UnknownItemError from the KeyError. Catch it for "eraser" and print the message and err.__cause__.

Solutions

Solution 1

def set_age(age):
    if age < 0 or age > 150:
        raise ValueError(f"age must be between 0 and 150, got {age}")
    return age


for age in [25, -1, 200]:
    try:
        print("Saved age:", set_age(age))
    except ValueError as err:
        print("Error:", err)
Saved age: 25
Error: age must be between 0 and 150, got -1
Error: age must be between 0 and 150, got 200

The message includes the bad value, so the user knows what to fix.

Solution 2

class PasswordError(Exception):
    """Base class for password problems."""


class TooShortError(PasswordError):
    pass


class NoDigitError(PasswordError):
    pass


def check_password(password):
    if len(password) < 8:
        raise TooShortError(f"password has {len(password)} characters, needs at least 8")
    if not any(char.isdigit() for char in password):
        raise NoDigitError("password needs at least one digit")
    return True


for password in ["cat", "sunflower", "sunflower7"]:
    try:
        check_password(password)
        print(f"{password!r}: OK")
    except PasswordError as err:
        print(f"{password!r}: {type(err).__name__}: {err}")
'cat': TooShortError: password has 3 characters, needs at least 8
'sunflower': NoDigitError: password needs at least one digit
'sunflower7': OK

One except PasswordError catches both subclasses, and type(err).__name__ shows which one it was.

Solution 3

class UnknownItemError(Exception):
    pass


prices = {"pen": 1.5, "notebook": 3.0}


def get_price(item):
    try:
        return prices[item]
    except KeyError as err:
        raise UnknownItemError(f"we do not sell {item!r}") from err


try:
    get_price("eraser")
except UnknownItemError as err:
    print("Error:", err)
    print("Cause:", repr(err.__cause__))
Error: we do not sell 'eraser'
Cause: KeyError('eraser')

from err stored the original KeyError in __cause__.

Common mistakes

  • Raising a string. raise "quantity must be at least 1" fails with TypeError: exceptions must derive from BaseException. Raise an exception object: raise ValueError("...").
  • A bare raise outside except. With no error being handled, it fails with RuntimeError: No active exception to reraise. Write the exception you mean, such as raise ValueError("...").
  • Inheriting from BaseException. except Exception does not catch such an error, so our test program crashed with ShopError: out of pens. The docs say to derive from Exception, “and not from BaseException“.
  • Forgetting super().__init__(message). Our OutOfStockError without it printed Message: ('notebook', 2) instead of a readable message.
  • The general except first. With except ShopError before except OutOfStockError, the second block never runs; our test printed General shop problem: only 2 notebook left.

Frequently asked questions

How do I create a custom exception in Python?

Write a class that inherits from Exception: class OutOfStockError(Exception): pass. Then raise it with a message, raise OutOfStockError("only 2 left"), and catch it with except OutOfStockError. Give it a name ending in Error.

What is the difference between raise and raise from in Python?

raise NewError(...) inside except still keeps the old error in __context__ and prints “During handling of the above exception, another exception occurred”. raise NewError(...) from err sets __cause__ and prints “The above exception was the direct cause of the following exception”, which tells the reader the change was on purpose.

Should I raise an exception or return None?

Raise when the caller gave bad input or asked for something that must exist; an error stops the program at the real problem. Return None only when “not found” is a normal result that the caller is expected to check, as with dict.get().

Summary

  • raise ValueError("message") stops a function and reports a problem; choose the built-in error that fits (ValueError for bad values, TypeError for wrong types).
  • A bare raise inside except re-raises the same error with its original traceback.
  • raise NewError(...) from err marks the old error as the cause (__cause__); from None hides it from the traceback.
  • A custom exception is a class that inherits from Exception; a base class like ShopError lets callers catch a whole family, and __init__ can add attributes.
  • Raise for real problems, return None only for normal “not found” answers, and use add_note() to add context before re-raising.

Next lesson

Next: Lesson 37, Python Debugging and Logging: breakpoint(), pdb and the logging Module.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *