Python Errors and Exceptions · Lesson 98 of 149

Python raise and Custom Exceptions

What you will learn

  • Raising an exception with raise
  • Choosing the right built-in exception
  • Re-raising with a bare raise
  • Writing custom exception classes, with extra data
  • Building an exception hierarchy

1. raise

So far, Python raised the errors. You can raise one yourself when your function is given something it cannot accept. This is better than returning a vague value or carrying on with bad data:

def set_age(a):
    if not isinstance(a, int):
        raise TypeError("age must be an int")
    if a < 0:
        raise ValueError(f"age cannot be negative: {a}")
    return a

for v in (5, -1, "x"):
    try:
        print(set_age(v))
    except (TypeError, ValueError) as e:
        print(type(e).__name__, e)
5
ValueError age cannot be negative: -1
TypeError age must be an int

The form is raise ExceptionClass("message"). Execution stops at the raise line, exactly as if Python had found the error, and the nearest matching except takes over.

You may also raise the class without brackets (raise ValueError); Python creates an object with no message:

try:
    raise ValueError
except ValueError as e:
    print(repr(e))
ValueError()

Only exceptions can be raised. Anything else is itself an error:

raise "text"
TypeError: exceptions must derive from BaseException
Quick check: what does a `raise` line do to the code below it in the same block?

That code is not run: control leaves the block at once.

2. Choosing a built-in type

Use the type that describes the problem, so callers can handle it correctly:

Situation Raise
the value has the right type but is unacceptable (negative age, empty name) ValueError
the value has the wrong type TypeError
a key or name is not found KeyError (mapping), IndexError (position) or LookupError
a feature is not written yet, or a subclass must supply a method NotImplementedError (lesson 13.5)
a state makes the call invalid (closing a closed file) RuntimeError or your own type
a file or system problem OSError family (usually raised by Python itself)

Do not raise the bare Exception for something specific, and do not use an assert for input checks (lesson 14.5).

Write helpful messages: say what was wrong and the value, such as f"age cannot be negative: {a}".

3. Re-raising

Sometimes you want to do something when an error occurs (log it, clean up) and still let the error continue upward. A bare raise inside an except block re-raises the same exception:

try:
    try:
        int("x")
    except ValueError:
        print("logging it")
        raise
except ValueError as e:
    print("re-raised:", e)
logging it
re-raised: invalid literal for int() with base 10: 'x'

The traceback is kept, so the original location is not lost. (Lesson 14.7 covers raise ... from ... for turning one error into another.)

4. Custom exception classes

Built-in types do not always say enough. A banking program might want InsufficientFunds; a library program might want BookNotFound. Exceptions are classes, so make your own by inheriting from Exception (lesson 13.5):

class Plain(Exception):
    pass

try:
    raise Plain()
except Plain as e:
    print(repr(e), str(e) == "")
Plain() True

An empty class body is enough: the new class gets everything an exception needs, and can be raised and caught by name. Inherit from Exception, not BaseException.

Conventions:

  • Name them with an Error ending (or a clear noun like Timeout): InsufficientFundsError, ConfigError. Python's own are mixed, so clarity matters most.
  • Put a one-line docstring to say when it is raised.

Adding data

Pass a message to super().__init__ and store any extra facts as attributes, so the handler can use them instead of parsing text (lesson 13.6):

class AppError(Exception):
    """Base for this app."""

class InsufficientFunds(AppError):
    def __init__(self, balance, needed):
        super().__init__(f"balance {balance} is less than {needed}")
        self.balance, self.needed = balance, needed

    @property
    def shortfall(self):
        return self.needed - self.balance

try:
    raise InsufficientFunds(30, 100)
except AppError as e:
    print(type(e).__name__, "|", e)
    print(e.shortfall, e.args)
InsufficientFunds | balance 30 is less than 100
70 ('balance 30 is less than 100',)

Use it in code that really handles the error:

class Account:
    def __init__(self, b):
        self.balance = b

    def withdraw(self, n):
        if n <= 0:
            raise ValueError("amount must be positive")
        if n > self.balance:
            raise InsufficientFunds(self.balance, n)
        self.balance -= n
        return self.balance

acc = Account(100)
for amt in (30, 0, 500, 70):
    try:
        print("left:", acc.withdraw(amt))
    except InsufficientFunds as e:
        print("short by", e.shortfall)
    except ValueError as e:
        print("invalid:", e)
left: 70
invalid: amount must be positive
short by 430
left: 0

5. A hierarchy of your own

Give a program or library one base exception, and derive the specific ones from it:

Exception
└── AppError                 (base for the whole program)
    ├── NotFound
    └── InsufficientFunds

Then callers have a choice:

  • catch a specific one, when they know how to recover;
  • catch AppError to handle any error from your code, without catching unrelated bugs such as TypeError:
class NotFound(AppError):
    pass

try:
    raise NotFound("user 7")
except AppError as e:
    print(repr(e))
NotFound('user 7')

This is how well-known libraries do it. A custom exception can also inherit from a built-in one to stay compatible with code that catches that type:

class Timeout(AppError, TimeoutError):
    pass

try:
    raise Timeout("slow")
except OSError as e:
    print("caught as OSError:", e)
caught as OSError: slow

(TimeoutError is a kind of OSError.)

6. Guidelines

Do Do not
raise exceptions for errors, return values for normal results use exceptions for ordinary flow in common cases
pick the most specific sensible type raise bare Exception for everything
write clear messages with the bad value write "error" or "invalid"
make one base class per program or package create a new unrelated class for every case
keep data in attributes force callers to parse message text
document which exceptions a function raises (docstring) surprise callers

Worked example: borrowing books

A small library has its own error family. borrow raises a specific error for each problem. The calling loop handles the two it can explain, and falls back to the base class for the rest.

class LibraryError(Exception):
    """Base class for every error raised by this library program."""


class BookNotFound(LibraryError):
    def __init__(self, title):
        super().__init__(f"no book called {title!r}")
        self.title = title


class AlreadyBorrowed(LibraryError):
    def __init__(self, title, holder):
        super().__init__(f"{title!r} is already borrowed by {holder}")
        self.holder = holder


class LimitReached(LibraryError):
    pass


class Library:
    LIMIT = 2

    def __init__(self, titles):
        self.loans = {t: None for t in titles}

    def borrow(self, title, member):
        if title not in self.loans:
            raise BookNotFound(title)
        holder = self.loans[title]
        if holder is not None:
            raise AlreadyBorrowed(title, holder)
        if list(self.loans.values()).count(member) >= self.LIMIT:
            raise LimitReached(f"{member} already has {self.LIMIT} books")
        self.loans[title] = member


lib = Library(["Dune", "Emma", "Ulysses", "Hamlet"])
requests = [("Dune", "Rina"), ("Dune", "Sam"), ("Moby", "Sam"),
            ("Emma", "Rina"), ("Ulysses", "Rina"), ("Hamlet", "Sam")]

for title, who in requests:
    try:
        lib.borrow(title, who)
    except AlreadyBorrowed as e:
        print("Taken:", e, "| holder:", e.holder)
    except LibraryError as e:
        print(f"{type(e).__name__}: {e}")
    else:
        print(f"{who} borrowed {title}")

print(lib.loans)
Rina borrowed Dune
Taken: 'Dune' is already borrowed by Rina | holder: Rina
BookNotFound: no book called 'Moby'
Rina borrowed Emma
LimitReached: Rina already has 2 books
Sam borrowed Hamlet
{'Dune': 'Rina', 'Emma': 'Rina', 'Ulysses': None, 'Hamlet': 'Sam'}
Part What it shows
LibraryError one base class for the whole program
BookNotFound, AlreadyBorrowed extra data kept as attributes (title, holder)
except AlreadyBorrowed before except LibraryError specific handler first, then the general one
else the success message, only when no error occurred
Library.borrow the checks live in one place, and raise instead of returning codes

The titles and names are made up.

Common mistakes

  • Raising Exception("something") for everything.
  • Using the wrong type (ValueError for a wrong type, or a KeyError for a bad value).
  • Vague messages such as "invalid".
  • Writing raise e instead of a bare raise when re-raising (it works, but adds an extra traceback entry for the raise e line).
  • Subclassing BaseException.
  • Returning an error code or None where an exception would be clearer.
  • Listing the base class before the specific one in except.

Key takeaways

  • raise Type("message") stops the current code and signals an error; a bare raise inside except re-raises the same one.
  • Choose the built-in type that matches the problem (ValueError, TypeError, KeyError...), with a message that shows the bad value.
  • Custom exceptions inherit from Exception; store extra facts as attributes.
  • Give a program one base exception and derive the specific ones, so callers can catch a precise error or the whole family.
  • Specific except clauses go before general ones.

Practice

1. Write a function sqrt_safe(x) that raises ValueError for negative x.

Show answer
def sqrt_safe(x):
    if x < 0:
        raise ValueError(f"cannot take the square root of {x}")
    return x ** 0.5

2. What does a bare raise do, and where is it allowed?

Show answer

Inside an except block it re-raises the exception being handled, keeping its traceback.

3. Define an exception OutOfStock with a item attribute.

Show answer
class OutOfStock(Exception):
    def __init__(self, item):
        super().__init__(f"{item} is out of stock")
        self.item = item

4. Why create one base class for all your program's exceptions?

Show answer

Callers can catch the whole family with one except AppError, without also catching unrelated bugs, or catch a specific subclass when they know what to do.

5. Which should come first, except LibraryError or except AlreadyBorrowed?

Show answer

except AlreadyBorrowed. The first matching clause wins, so the general one would hide it.

6. Which built-in type fits "age is -5"? And "age is the text 'five'"?

Show answer

ValueError for -5 (right type, bad value); TypeError for 'five' (wrong type).