Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 44 of 70

Raising and defining your own exceptions in Python

Use raise to signal a problem from your own functions, chain exceptions, and define custom exception classes that make errors clear to the caller.

13 minErrors and filesUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonRaise built-in exceptions with clear messages, define a custom exception class, and re-raise or chain errors correctly.

After this lesson you will be able to make your own functions report problems clearly, and create exception types that describe the problems of your own program. So far Python raised every error for you. Now you take control.

Raising an exception

The raise statement creates an exception and stops the current function. Give it a type and a message.

python
def set_quantity(quantity):
    if quantity < 0:
        raise ValueError("quantity cannot be negative")
    return quantity

print(set_quantity(5))
result
5
python
set_quantity(-2)
result
ValueError: quantity cannot be negative

A function that raises is saying "I cannot do this with what you gave me". The caller then decides: handle it with try, or let the program stop.

python
try:
    set_quantity(-2)
except ValueError as err:
    print("Rejected:", err)
result
Rejected: quantity cannot be negative

Choose the built-in type that matches the problem. ValueError suits a bad value, TypeError a wrong kind of argument, KeyError a missing key and FileNotFoundError a missing file. Write the message for a person who will read it later: say what was wrong and, if useful, what was received.

python
def apply_discount(price, percent):
    if not 0 <= percent <= 100:
        raise ValueError(f"percent must be between 0 and 100, got {percent}")
    return price * (100 - percent) / 100

print(apply_discount(80, 25))
result
60.0
python
apply_discount(80, 150)
result
ValueError: percent must be between 0 and 100, got 150

Defining your own exception

Built-in types cover many cases, but sometimes the problem belongs to your program: an out-of-stock item, an overdue library book. A custom exception is just a class that inherits from Exception. (Classes are explained in the object-oriented section, so treat this as a pattern to copy for now.)

python
class OutOfStock(Exception):
    pass

def sell(stock, item, amount):
    if stock.get(item, 0) < amount:
        raise OutOfStock(f"only {stock.get(item, 0)} of {item} left")
    stock[item] -= amount
    return stock[item]

stock = {"pens": 3}
print(sell(stock, "pens", 2))
result
1
python
sell(stock, "pens", 5)
result
OutOfStock: only 1 of pens left

The benefit is that callers can catch exactly this problem and nothing else:

python
try:
    sell(stock, "pens", 5)
except OutOfStock as err:
    print("Cannot sell:", err)
result
Cannot sell: only 1 of pens left

A tidy habit is to make one base class for a whole program, then derive more specific ones from it. Callers can then catch either the narrow type or the whole family.

python
class LibraryError(Exception):
    pass

class BookNotFound(LibraryError):
    pass

class BookAlreadyBorrowed(LibraryError):
    pass

def borrow(catalogue, title):
    if title not in catalogue:
        raise BookNotFound(title)
    if catalogue[title]:
        raise BookAlreadyBorrowed(title)
    catalogue[title] = True
    return "Enjoy " + title

catalogue = {"Dune": False, "Emma": True}
for title in ["Dune", "Emma", "Ulysses"]:
    try:
        print(borrow(catalogue, title))
    except BookAlreadyBorrowed:
        print(title, "is already out")
    except LibraryError:
        print(title, "is not in the library")
result
Enjoy Dune
Emma is already out
Ulysses is not in the library

Because BookNotFound inherits from LibraryError, the last except catches it.

Re-raising and chaining

Sometimes you want to react to an error and still let it continue upwards, for example to log it. A bare raise inside an except block does that, with the original traceback intact.

python
def read_count(text):
    try:
        return int(text)
    except ValueError:
        print("Logging: bad count", repr(text))
        raise

try:
    read_count("many")
except ValueError as err:
    print("Caller saw:", err)
result
Logging: bad count 'many'
Caller saw: invalid literal for int() with base 10: 'many'

You can also turn a low-level error into a clearer one, keeping the original as the cause with from:

python
class ConfigError(Exception):
    pass

def read_port(text):
    try:
        return int(text)
    except ValueError as err:
        raise ConfigError("port must be a whole number") from err

try:
    read_port("http")
except ConfigError as err:
    print(err)
    print("Caused by:", repr(err.__cause__))
result
port must be a whole number
Caused by: ValueError("invalid literal for int() with base 10: 'http'")

assert is for your own assumptions

assert condition, message raises an AssertionError when the condition is false. Use it to document things that must be true if your code is correct, mostly while developing. Do not use it to check user input: assertions can be switched off when Python runs with the -O option, and a check that disappears is not a check.

python
def average(numbers):
    assert len(numbers) > 0, "average needs at least one number"
    return sum(numbers) / len(numbers)

print(average([4, 6, 8]))
result
6.0
python
average([])
result
AssertionError: average needs at least one number

Common mistakes

  • Raising the bare Exception class. raise Exception("bad") forces callers to catch everything. Use a specific built-in or a custom type.
  • A vague message. raise ValueError("error") helps nobody. Say what was wrong and what you received.
  • Using exceptions for normal flow. If a case happens all the time, handle it with an if instead of raising and catching.
  • Writing raise err when you mean raise. In most cases a bare raise keeps the original traceback and is the clearer choice.
  • Validating user input with assert. Use if and raise for input checks, because assertions can be disabled.

Exercise

Define an exception InvalidMark and a function grade(mark) that raises it when the mark is below 0 or above 100, otherwise returns "pass" for 40 or more and "fail" below 40. Call it with 72, 25 and 130, catching the error for the last one.

Show one possible answer
python
class InvalidMark(Exception):
    pass

def grade(mark):
    if mark < 0 or mark > 100:
        raise InvalidMark(f"mark must be 0 to 100, got {mark}")
    return "pass" if mark >= 40 else "fail"

for mark in [72, 25, 130]:
    try:
        print(mark, grade(mark))
    except InvalidMark as err:
        print("Invalid:", err)
result
72 pass
25 fail
Invalid: mark must be 0 to 100, got 130

Next: reading files puts error handling to work, because files are where things often go wrong. A video version of this topic is in the video course at /learn/python/.

Key points

  • raise ExceptionType(message) stops the current function and signals a problem to whoever called it.
  • Pick the built-in type that fits, such as ValueError for a bad value, and write a message that says what was wrong.
  • A custom exception is a class that inherits from Exception. It lets callers catch your specific problem.
  • A bare raise inside except re-raises the same error, and raise NewError from err chains a cause onto a new one.
  • assert is for checking your own assumptions while developing, not for validating user input.

Check yourself

1. What does a bare raise do inside an except block?
2. A function receives a negative quantity, which makes no sense. Which built-in type fits best?
3. How do you define a custom exception?
4. What does raise NewError('x') from err record?