Skip to contentSkip to navigation

Module 09 · Lesson 03

Raising and Defining Your Own Exceptions

Make your functions report problems clearly: raise built-in exceptions with good messages, define your own exception classes, group them in a small family, and chain them with raise from.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Raise with a message
  • Define your own
  • Catch a family
  • Watch a raise travel

Raise your own alarms

Your code can stop with a clear message too, using `raise`. You can even invent new kinds of error.

  • raise

    raise ValueError("age must be 0 or more") stops right here with your message.

  • Pick a type

    ValueError for a bad value, TypeError for the wrong kind, KeyError for a missing key.

  • Your own class

    class SoldOut(Exception): pass makes a brand new exception type.

  • A family

    Give related exceptions one parent class, then catch them all with one except.

Custom errors everywhere

Big programs name their own problems, so the code that catches them knows exactly what happened.

  • Online shopsSoldOut and CardDeclined can both belong to a CheckoutError family.
  • GamesNotEnoughCoins stops a purchase with a message the player understands.
  • Booking appsDateTaken explains exactly why a booking failed.
  • LibrariesBig Python packages define their own exceptions so you can catch just theirs.

A raise with a helpful message

This line stops a function on purpose. Tap each part to see its job.

Part 1 of 3

Tap any part of the code below, or press Next.1 of 3 explored

raise:Stops this function now and sends the exception up to whoever called it.

Raise and define exceptions

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6raise

raise stops the function with your own message. The caller decides what to do about it.

Your turn: Also reject ages over 130 with a different message.

Python
def set_age(age):
    if age < 0:
        raise ValueError(f"age must be 0 or more, got {age}")
    return age

print(set_age(12))
try:
    set_age(-3)
except ValueError as e:
    print("Problem:", e)
Output
Press Run to see what it prints.

Watch a raise travel

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. class NameTooShort(Exception):
  2. pass
  3. def sign_up(name):
  4. if len(name) < 3:
  5. raise NameTooShort(f"{name} has {len(name)} letters")
  6. return "hello " + name
  7. for name in ["Maya", "Al"]:
  8. try:
  9. print(sign_up(name))
  10. except NameTooShort as e:
  11. print("try again:", e)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.A KeyError's message:

try:
    raise KeyError("color")
except KeyError as e:
    print(e)

0 of 6 answered

Common custom exception misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Raising an exception yourself

You have seen Python raise exceptions; your own code can raise them as well, with the raise statement:

Try it 1: edit me, then Run
def set_age(age):
    if age < 0:
        raise ValueError(f"age cannot be negative, got {age}")
    return age

set_age(-3)
# ValueError: age cannot be negative, got -3
Output
Press Run to see what it prints.

raise stops the function immediately, like return, but instead of handing back a value it sends an exception up to the caller. If nobody catches it, the program stops with a traceback that shows your message. A good message says what was wrong and, if it helps, what value caused it.

Choosing a built-in exception

Often a built-in type fits perfectly, and callers already know what it means:

Situation Exception
right type, unacceptable value ValueError
wrong type of argument TypeError
missing key or item KeyError, LookupError
something not supported yet NotImplementedError

Raising a well-known type means a caller's except ValueError: handles your problem along with Python's own.

Defining your own exception

When the problem belongs to your program, such as an order that is out of stock, a custom exception explains itself better than a generic one. Defining one takes two lines:

Try it 2: edit me, then Run
class OutOfStockError(Exception):
    pass

raise OutOfStockError("only 2 mugs left")
Output
Press Run to see what it prints.

class OutOfStockError(Exception): creates a new kind of exception that is a kind of Exception, so it behaves like every other exception: it can be raised, caught and given a message. pass means the class needs nothing extra. You will learn much more about classes in the next module; for exceptions, this short form is all you need. By convention the name ends in Error.

Catching it works exactly as with built-in exceptions:

Try it 3: edit me, then Run
try:
    raise OutOfStockError("only 2 mugs left")
except OutOfStockError as error:
    print("Sorry:", error)     # Sorry: only 2 mugs left
Output
Press Run to see what it prints.

A family of exceptions

Bigger programs usually define one base exception and several more specific ones that inherit from it:

Try it 4: edit me, then Run
class ShopError(Exception):
    pass

class OutOfStockError(ShopError):
    pass

class PaymentError(ShopError):
    pass
Output
Press Run to see what it prints.

Now callers can choose how precise to be. except OutOfStockError: handles only stock problems, while except ShopError: handles anything the shop raises. Because OutOfStockError is a kind of ShopError, which is a kind of Exception, it matches all three. This is the same idea as except LookupError: catching both KeyError and IndexError.

Order matters when you list several except blocks: put the specific ones first. Python checks them top to bottom and runs the first match, so an except ShopError: written first would also swallow the stock errors meant for the next block.

Raising from another exception

Sometimes a low-level error is really a sign of a higher-level problem. A KeyError while looking up a product code means "unknown product" to your users. You can translate it with raise ... from ...:

Try it 5: edit me, then Run
PRICES = {"mug": 6.5}

def price_of(code):
    try:
        return PRICES[code]
    except KeyError as error:
        raise ShopError(f"unknown product {code!r}") from error
Output
Press Run to see what it prints.

The new exception carries the original as its cause, and a traceback shows both: first the KeyError, then the line "The above exception was the direct cause of the following exception", then the ShopError. Callers deal with one clear shop-level error, while whoever is debugging still sees the original detail.

Raising versus returning a special value

Compare two designs for a function that withdraws money:

Try it 6: edit me, then Run
def withdraw_v1(balance, amount):
    if amount > balance:
        return None            # caller must remember to check
    return balance - amount

def withdraw_v2(balance, amount):
    if amount > balance:
        raise ValueError("insufficient funds")
    return balance - amount
Output
Press Run to see what it prints.

With the first, a caller who forgets the check carries on with None and fails somewhere later, far from the cause. With the second, the problem cannot be ignored: either the caller handles ValueError, or the program stops right at the source. Raise when the caller cannot sensibly continue as if nothing happened; return a value when "nothing found" is an ordinary, expected answer, as dict.get does.

Where to raise and where to catch

A useful rule: raise where you detect the problem, and catch where you know what to do about it. A function deep inside a program usually cannot decide whether to retry, ask the user or give up, so it raises. The top of the program, or the part that talks to the user, catches the exception and chooses the response. That keeps each function simple and honest.

Syntax

The general shape of the statements in this lesson.

syntax.py
raise ValueError("clear message")       # raise a built-in
class AppError(Exception):               # your own base exception
    pass
class NotFoundError(AppError):           # a more specific one
    pass
raise NotFoundError("no such user")
except NotFoundError as e:               # precise
except AppError:                         # the whole family
raise AppError("unknown code") from err  # translate, keep the cause
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Validating a sign-up form

Beginner

Write a check that raises a clear exception for each kind of bad sign-up data, and report the problem for several attempts without stopping.

Python
class SignupError(Exception):
    pass

class UsernameError(SignupError):
    pass

class PasswordError(SignupError):
    pass

def check_signup(username, password):
    if len(username) < 3:
        raise UsernameError("username needs at least 3 characters")
    if not username.isalnum():
        raise UsernameError("username may only use letters and digits")
    if len(password) < 8:
        raise PasswordError("password needs at least 8 characters")
    return "welcome " + username

attempts = [("al", "secret123"), ("ana!", "secret123"), ("ana", "short"), ("ana", "secret123")]
for username, password in attempts:
    try:
        print(check_signup(username, password))
    except SignupError as error:
        print(f"{type(error).__name__}: {error}")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The check function only detects problems and raises; it never prints. The loop catches the base SignupError, so both kinds of problem are handled by one except, and type(error).__name__ still shows which kind it was.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Catching the base class first

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
try:
    raise OutOfStockError('no mugs')
except ShopError:
    print('shop problem')
except OutOfStockError:
    print('restock')
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints shop problem; the restock branch can never run

Write this instead

try:
    raise OutOfStockError('no mugs')
except OutOfStockError:
    print('restock')
except ShopError:
    print('shop problem')

Why it happens

OutOfStockError is a kind of ShopError, so the first except already matches it.

In the real world

Where this shows up in software people use every day.

  1. An inventory service with its own errors

    Warehousing

    A warehouse's stock module is used by the website, the till and the delivery app. Each of those programs reacts differently to problems, so the module raises clear errors and leaves the reaction to them.

    Why Python fits

    The stock module never prints or decides; it only raises. This caller back-orders shortages and rejects unknown items, while another program could catch the base StockError and show one general message.

    Python
    class StockError(Exception):
        pass
    
    class UnknownItemError(StockError):
        pass
    
    class NotEnoughStockError(StockError):
        pass
    
    stock = {"mug": 4, "lamp": 0}
    
    def take(item, qty):
        if item not in stock:
            raise UnknownItemError(f"no item called {item!r}")
        if stock[item] < qty:
            raise NotEnoughStockError(f"{item}: wanted {qty}, have {stock[item]}")
        stock[item] -= qty
        return stock[item]
    
    orders = [("mug", 3), ("lamp", 1), ("rug", 1), ("mug", 2)]
    for item, qty in orders:
        try:
            left = take(item, qty)
            print(f"took {qty} {item}, {left} left")
        except NotEnoughStockError as error:
            print("back-order:", error)
        except UnknownItemError as error:
            print("rejected:", error)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Should I always make my own exception class?

No. If ValueError or TypeError already describes the problem, use it. Create your own when the problem belongs to your program's domain, or when callers need to catch your errors separately from Python's.

Can my exception carry extra data, like the item name?

Yes, by giving the class an __init__ method that stores attributes. The classes lessons in the next module explain __init__ and self.

How many custom exceptions should a program have?

As few as callers actually need to tell apart. One base class plus a handful of specific ones is typical. If no caller would ever catch a subclass separately, the base class with a clear message is enough.

What is the difference between Exception and BaseException?

BaseException also covers signals such as KeyboardInterrupt, which should normally stop a program. Always inherit your exceptions from Exception.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.