Sub topic 3
The exception hierarchy: BaseException, Exception, and subclasses
This chapter assumes you can write and call functions, use if, for, and while, read a simple traceback, and write a basic class with inheritance. You should also know the basic try/except form from the previous chapter. Here you will learn how Python arranges its exception classes into a tree, and why that tree decides what an except clause catches.
Exceptions are classes in a tree
Every exception is an instance of a class, and every exception class inherits from BaseException. An except clause matches by isinstance. If you write except LookupError, it catches any exception whose class is LookupError or a subclass of it. The tree therefore works as a grouping system: a parent class names a family of failures, and catching the parent catches all of them.
The diagram shows the top of the tree and a few of the families you will meet most often.
BaseException versus Exception
The split at the top of the tree is deliberate.
BaseExceptionis the root. It exists so that the interpreter can use exceptions for events that are not errors in your program.Exceptionis the root for ordinary errors. Almost everything you catch in application code, and every exception you define yourself, belongs under it.
The direct children of BaseException other than Exception signal that the program or thread should stop:
| Class | Raised when |
|---|---|
| `SystemExit` | `sys.exit()` is called, or `exit()` in a script |
| `KeyboardInterrupt` | The user presses Ctrl+C |
| `GeneratorExit` | A generator is closed while suspended |
| `BaseExceptionGroup` | Several exceptions are bundled together (Python 3.11+) |
asyncio.CancelledError also inherits from BaseException (since Python 3.8), so a task cancellation is not swallowed by except Exception.
Because these classes sit outside Exception, the handler except Exception lets them pass. That is the behavior you want: a loop that logs and continues on errors should still stop when the user presses Ctrl+C.
try:
raise KeyboardInterrupt
except Exception:
print("not reached")
except BaseException as exc:
print(f"caught {type(exc).__name__}")This prints caught KeyboardInterrupt. The first handler does not match because KeyboardInterrupt is not an Exception.
Inspecting a class's ancestors
Every class records its ancestry in __mro__ (method resolution order), a tuple that starts with the class and ends with object. You can print the ancestry of any exception without looking it up in the documentation.
for exc_type in (FileNotFoundError, KeyError, ZeroDivisionError, KeyboardInterrupt):
chain = " -> ".join(cls.__name__ for cls in exc_type.__mro__)
print(chain)The output is:
FileNotFoundError -> OSError -> Exception -> BaseException -> object
KeyError -> LookupError -> Exception -> BaseException -> object
ZeroDivisionError -> ArithmeticError -> Exception -> BaseException -> object
KeyboardInterrupt -> BaseException -> objectYou can also ask a direct question with issubclass(FileNotFoundError, OSError), which returns True. This is the same test that except performs.
Catching a family with a parent class
Catching a parent class is useful when different failures call for the same response. KeyError and IndexError both mean "the item you asked for is not there", and both inherit from LookupError.
data = {"a": [1, 2]}
def fetch(key, index):
try:
return data[key][index]
except LookupError as exc:
print(f"{type(exc).__name__}: {exc}")
return None
fetch("b", 0)
fetch("a", 5)The output is:
KeyError: 'b'
IndexError: list index out of rangeOne handler covers both cases, and type(exc).__name__ still tells you which one occurred. The same idea applies to ArithmeticError, which covers ZeroDivisionError, OverflowError, and FloatingPointError.
The families you will meet most
Knowing the main families lets you pick the right level of handler without searching the documentation each time.
| Parent | Notable subclasses | Typical cause |
|---|---|---|
| `OSError` | `FileNotFoundError`, `PermissionError`, `FileExistsError`, `TimeoutError`, `ConnectionError` | Files, sockets, and other operating system calls |
| `LookupError` | `KeyError`, `IndexError` | Missing key or position |
| `ArithmeticError` | `ZeroDivisionError`, `OverflowError` | Numeric operations |
| `ValueError` | `UnicodeError`, `json.JSONDecodeError` | Right type, unacceptable value |
| `NameError` | `UnboundLocalError` | Using a name that has no value |
| `ImportError` | `ModuleNotFoundError` | A failed `import` |
| `RuntimeError` | `NotImplementedError`, `RecursionError` | General runtime failures |
Several of these are worth a closer look:
OSErroris the parent of many specific file and network errors. The old namesIOErrorandEnvironmentErrorare aliases for it, soIOError is OSErrorisTrue. Code that catchesOSErrortherefore also handlesFileNotFoundErrorandPermissionError.TypeErrormeans the wrong kind of object was used, such as"a" + 1.ValueErrormeans the type was fine but the value was not, such asint("abc"). These two are not related by inheritance.AttributeError,AssertionError,StopIteration,EOFError, andMemoryErrorall inherit directly fromExceptionor from a small parent. They are siblings of the families above.- Warnings are also
Exceptionsubclasses (Warning,DeprecationWarning). They are normally reported without being raised, but they become real exceptions if you run Python with-W error.
The complete list is in the "Built-in Exceptions" page of the Python documentation. The tree is stable across versions, with additions such as ModuleNotFoundError (3.6) and BaseExceptionGroup (3.11).
Where your own exceptions belong
A class you define for your application should inherit from Exception, or from a more specific subclass if one fits.
class ConfigError(Exception):
"""Raised when configuration is invalid."""
class MissingSettingError(ConfigError):
"""Raised when a required setting is absent."""
try:
raise MissingSettingError("DATABASE_URL")
except ConfigError as exc:
print(f"{type(exc).__name__}: {exc}")This prints MissingSettingError: DATABASE_URL. Handlers written for ConfigError also cover MissingSettingError, which is the same grouping behavior that the built-in tree provides. A later chapter covers custom exceptions in more detail. For now, remember that inheriting from BaseException is almost always a mistake, because it makes your error slip past except Exception handlers in other people's code.
Common errors
These mistakes come from not knowing the shape of the tree.
- Catching too high.
except Exceptionaround a large block also hides bugs such asAttributeErrorandNameError. Prefer the narrowest class that describes the failure you expect. - Catching too low. Writing
except FileNotFoundErrorwhen the code can also fail withPermissionErrorleaves the second case uncaught. If both mean "the file could not be read", catchOSError. - Assuming siblings are related.
KeyErroris not aValueError, andTypeErroris not aValueError. A handler for one does not catch the other. - Forgetting that order matters. If a parent handler comes before a child handler, the child handler can never run, because the parent matches first. The next chapter covers this in detail.
- Subclassing
BaseExceptionfor application errors. UseExceptioninstead.
Summary
All exceptions descend from BaseException. Ordinary errors descend from Exception, while SystemExit, KeyboardInterrupt, and GeneratorExit sit beside it so that broad handlers do not intercept them. An except clause matches the named class and all of its subclasses, so parent classes such as OSError, LookupError, and ArithmeticError let you handle a whole family at once.
Exercise
A function reads a file with open(path) and you want a single except clause that handles a missing file, a permissions problem, and a path that is a directory, without catching KeyboardInterrupt. Which class should you name, and why does it work? Also, what does except: with no class do differently?
Show answer
Name OSError. FileNotFoundError, PermissionError, and IsADirectoryError are all subclasses of OSError, and OSError inherits from Exception, not directly from BaseException, so KeyboardInterrupt is not matched. A bare except: is the same as except BaseException:, so it would also catch KeyboardInterrupt and SystemExit.
Exercise
Predict the output, then explain it. try: {}["x"] except IndexError: print("index") except LookupError: print("lookup")
Show answer
It prints lookup. Looking up a missing dictionary key raises KeyError. KeyError is not a subclass of IndexError, so the first clause does not match. It is a subclass of LookupError, so the second clause matches.