Sub topic 3
The exception hierarchy: BaseException, Exception, and subclasses
This chapter assumes you can write and call functions, use basic if/for/while control flow, read a simple traceback, and define a class that inherits from another. It also assumes you know the basic try/except form from the previous chapter.
Exceptions are classes in a tree
Every exception in Python is an instance of a class, and those classes form an inheritance tree. At the top is BaseException. An except clause names a class, and it catches any exception that is an instance of that class or of one of its subclasses. So the position of a class in the tree decides what a handler catches.
BaseException and Exception
BaseException is the root. Most of its direct children are not errors in your program. They are signals that the interpreter or the user wants to stop something:
KeyboardInterruptis raised when the user presses Ctrl+C.SystemExitis raised bysys.exit().GeneratorExitis raised inside a generator when it is closed.
Exception is the subclass for ordinary runtime errors. Nearly everything you meet day to day inherits from it, and your own exception classes should too. Catching Exception handles program errors while leaving Ctrl+C and sys.exit() alone.
Inspecting the tree
Every class has a __mro__ attribute, the chain of base classes Python searches. For an exception class, it lists the handlers that would match it.
import json
for exc in (ZeroDivisionError, KeyError, FileNotFoundError, json.JSONDecodeError):
chain = " > ".join(cls.__name__ for cls in exc.__mro__)
print(f"{exc.__name__}: {chain}")The output shows, for example, KeyError: KeyError > LookupError > Exception > BaseException > object. A handler for any class in that chain catches a KeyError.
Useful intermediate classes
Several mid-level classes group related errors, so one handler can cover them all.
| Parent class | Subclasses you will meet |
|---|---|
| `ArithmeticError` | `ZeroDivisionError`, `OverflowError` |
| `LookupError` | `KeyError`, `IndexError` |
| `OSError` | `FileNotFoundError`, `PermissionError`, `TimeoutError` |
| `ValueError` | `UnicodeError`, `json.JSONDecodeError` |
Catching the parent is useful when the cause does not matter to you:
def first_item(container, key):
try:
return container[key]
except LookupError:
return None
print(first_item({"a": 1}, "b"))
print(first_item([10, 20], 5))Both calls print None. The first raises KeyError and the second raises IndexError, and LookupError matches both. Note that OSError also has the older aliases IOError and EnvironmentError. They are the same class, so you will see them in older code.
How matching uses the tree
Python checks except clauses from top to bottom and runs the first one whose class matches. A parent listed before its child hides the child, because the parent already matches. Put the most specific classes first and the general ones after them.
try:
open("missing.txt")
except FileNotFoundError:
print("file is missing")
except OSError:
print("some other OS problem")If you swapped the two clauses, the FileNotFoundError handler would never run.
Common errors
- Inheriting from
BaseException. Custom errors that do this slip pastexcept Exceptionhandlers throughout the code that uses them. SubclassExceptioninstead. - Catching too high.
except Exceptionalso catches bugs such asNameErrorandAttributeError, which hides mistakes. Reserve it for boundaries such as a top-level job runner, and log what it catches. - Assuming a flat list. Learning only the leaf names means you miss parent classes such as
LookupErrorandOSErrorthat make handlers shorter.
Exercise
A function calls sys.exit(1) inside a try block that has only except Exception:. Does the handler run? Why or why not?
Show answer
No. sys.exit() raises SystemExit, which inherits from BaseException and not from Exception. The except Exception: clause does not match it, so the exit proceeds.
Exercise
Which single built-in class would you name in one except clause to catch both KeyError and IndexError, without also catching ValueError?
Show answer
LookupError. It is the common parent of KeyError and IndexError, and ValueError is not one of its subclasses.