Object-oriented programming · lesson 8 of 17
Parts in this lesson
Aclass LibraryError(Exception):the parent of the family
Bclass NotFound(LibraryError):one kind of library error
Cexcept LibraryError:catches the whole family
Derr.back_ondetails on the error
Eexcept ... as err:2.6: the error itself

Exception families

Last updated

When a loan goes wrong, there are different reasons: the book isn't in the catalogue, every copy is out, or the member already has three loans. Until now, every one of those has been a ValueError. In this lesson you'll see that errors are classes in a family tree, make a family of library errors of your own, catch a whole family with one except, put except blocks in the right order, and give an error details that the code catching it can use.

By the end of this lesson you can

  • Explain that exceptions are classes, and that catching a parent catches its children
  • Design a family of errors with one parent, LibraryError
  • Put except blocks in order, children before parents
  • Give an error attributes, so the code that catches it knows the details

Exceptions are classes

Every error you've met, ValueError, KeyError, TypeError, is a class. Raising one makes an object of that class. And like any classes, they're in families, with parents and children.

Step 1 code main.py
Edit the code, then run it again
  • Lines 1 and 2 print two MROs, as in lesson 4.7. KeyError and IndexError are both children of LookupError: the errors for looking something up and not finding it. Above that is Exception, the parent of every ordinary error.
  • Line 3: dividing by zero is a kind of arithmetic error.
  • Lines 6 to 9 look up a key that isn't there, which raises a KeyError. The except on line 8 names LookupError, and still catches it.

That's the rule this lesson is built on. except LookupError means "catch a LookupError, or any child of it", just as isinstance counts children in lesson 4.5. Line 9 uses type(err).__name__ to show which error was really caught.

The whole family tree of Python's own errors is in the documentation.

A family of library errors

The library makes a family of its own. At the top is LibraryError, a child of Exception, as in lesson 4.6. It isn't raised itself. It's there to be the parent.

Under it go three children, one for each way a loan can go wrong: NotFound, NotAvailable and LimitReached. A name that says what went wrong is most of the work, so each class is only pass.

A family of errors: every one is a LibraryError, and every LibraryError is an Exception
100%
LibraryError is an Exception
NotFound
NotAvailable
LimitReached
  • Class LibraryError; is a kind of Exception; no attributes of its own; no methods of its own.
  • Class NotFound; inherits from LibraryError; no attributes of its own; no methods of its own.
  • Class NotAvailable; inherits from LibraryError; no attributes of its own; no methods of its own.
  • Class LimitReached; inherits from LibraryError; no attributes of its own; no methods of its own.
Step 2 code main.py
Edit the code, then run it again
  • Line 17 shows the family line of NotFound.
  • Lines 18 and 19: every library error is a LibraryError, but Python's own errors aren't.
  • Line 20 makes an error object without raising it. raise is what stops the program. Line 21 shows the message it holds, and line 22 the family it belongs to.

Why not just use ValueError? Because then a program can't tell a library problem from a real mistake. If the code catching it says except ValueError, it also catches every ValueError from a typo in your own code, and hides it, as lesson 2.6 warned.

Catching a parent catches its children

Now the family is put to work. The errors and a Member class are in library.py. Open its tab. borrow() raises a different error for each problem: NotFound on line 26, NotAvailable on line 28, and LimitReached on line 30, when the member already has 3 loans.

The program tries to borrow six titles, with one except for the whole family.

Step 3 code
Edit the code, then run it again

Line 16 names only LibraryError, and it caught all three kinds. Each message came from the line that raised it, so one handler can show the right words for every problem.

A typo is still a typo. Change sam.borrow on line 14 to sam.borow and run it: the AttributeError isn't a LibraryError, so it isn't caught, and the traceback shows you the mistake.

The order of except blocks

Sometimes one kind of error needs its own answer. When a book is out, the library can offer a waiting list. When the member has too many loans, they need to give one back. A try can have several except blocks. Python checks them from the top down, and runs only the first one that matches.

Step 4 code
Edit the code, then run it again
  • Lines 7 and 9 catch two children, each with its own message.
  • Line 11 catches the parent. Any other library error ends up here, like NotFound for Persuasion.
  • Line 13: else runs only when nothing was raised, as in lesson 2.6.

So the rule is: children first, then the parent. The most specific handler goes at the top, and the catch-all for the family at the bottom.

The parent first

Here someone tidied the handlers and put the general one first. Press Run and look at what it says about Emma.

Step 5 code
Edit the code, then run it again

Python doesn't warn you about this. Handlers that can never run look just like ones that can. When you write several except blocks for one family, read them from the top and check that no handler comes after its own parent.

Adding details to an error

A message is for people to read. But the code that catches an error often needs the details too: which book, and when it'll be back. Store them as attributes, like any other object.

Step 6 code main.py
Edit the code, then run it again
  • Lines 6 to 9 give NotAvailable its own __init__. It takes the details, not a ready-made message.
  • Line 7 builds the message and passes it up to Exception's __init__ with super(), as in lesson 4.5, so the error still prints in plain words.
  • Lines 8 and 9 keep the details as attributes.
  • Line 17 raises it with only the details. The class writes the message, so every NotAvailable reads the same way.

Line 24 prints the message. Line 25 uses the details to say something new. Line 26 shows args, a tuple every error has with the values passed to Exception.__init__: here, the message.

Delete line 7 and run it again. Line 24 prints ('Dune', 18): with no message passed up, an error just shows the values it was made with. It's the same mistake as lesson 4.5: a child's __init__ should call its parent's.

In other languages

This step is optional. It's for anyone who will meet Java or Rust later.

Families of errors in three languages
PythonJavaRust
A family of errorsclass NotFound(LibraryError):class NotFound extends LibraryExceptionOne enum LibraryError, with a variant for each kind
Catching the whole familyexcept LibraryError:catch (LibraryException e)Handle the Result; match on the variant when the kind matters
A child after its parentRuns, but the child’s handler never doesWon’t compile: the child has already been caughtmatch warns about a pattern it can never reach
Saying what a function can raiseNot needed. Any function can raise anythingChecked exceptions: a method must catch them or list them with throws, and the compiler checksAlways, in the return type: Result<Loan, LibraryError>
DetailsAttributes on the errorFields on the exceptionFields in the variant

Java's checked exceptions are the biggest difference. If a Java method can throw a NotAvailable, it must say so with throws NotAvailable, and every caller must catch it or say the same. In Python, nothing tells you which errors a function might raise. You read its documentation, or its code.

C# works like Java, but without checked exceptions. Rust has no exceptions at all: a function that can fail returns its error as a value, which the caller has to deal with. Simple Rust teaches that when it gets to errors.

Check what you learned

Three questions. Pick or type an answer, then check it.

What does this program print?
class LibraryError(Exception):
    pass


class NotFound(LibraryError):
    pass


try:
    raise NotFound("no such book")
except LibraryError:
    print("library")
except NotFound:
    print("not found")
A menu should show library errors in plain words, but let real bugs stop the program. What should it catch?
NotAvailable has its own __init__(self, title, back_on). What must it do so that print(err) shows a message?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python