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
exceptblocks 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.
- Lines 1 and 2 print two MROs, as in lesson 4.7.
KeyErrorandIndexErrorare both children ofLookupError: the errors for looking something up and not finding it. Above that isException, 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. Theexcepton line 8 namesLookupError, 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.
- 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.
- 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.
raiseis 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.
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.
- 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
NotFoundfor Persuasion. - Line 13:
elseruns 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.
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.
- Lines 6 to 9 give
NotAvailableits own__init__. It takes the details, not a ready-made message. - Line 7 builds the message and passes it up to
Exception's__init__withsuper(), 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
NotAvailablereads 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.
| Python | Java | Rust | |
|---|---|---|---|
| A family of errors | class NotFound(LibraryError): | class NotFound extends LibraryException | One enum LibraryError, with a variant for each kind |
| Catching the whole family | except LibraryError: | catch (LibraryException e) | Handle the Result; match on the variant when the kind matters |
| A child after its parent | Runs, but the child’s handler never does | Won’t compile: the child has already been caught | match warns about a pattern it can never reach |
| Saying what a function can raise | Not needed. Any function can raise anything | Checked exceptions: a method must catch them or list them with throws, and the compiler checks | Always, in the return type: Result<Loan, LibraryError> |
| Details | Attributes on the error | Fields on the exception | Fields 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.
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.
- The Python Tutorial: User-defined Exceptions
- The Python Tutorial: Handling Exceptions: an except clause matches the class and its children, and the first match wins
- Built-in Exceptions: Exception hierarchy: the family tree of Python's own errors
- Built-in Exceptions: BaseException.args
- The Python Language Reference: The try statement
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Tutorials: The catch Blocks: catching an exception and its subclasses
- The Java Tutorials: Specifying the Exceptions Thrown by a Method: throws, and checked exceptions
- The Rust Programming Language: Error Handling: Result and panics in Rust, with no exceptions