Sub topic 1
How Python exceptions are organized
Before you define your own exception class, you need to know where it will sit. Every exception in Python belongs to one class hierarchy. That hierarchy decides what an except clause catches, what your program lets through, and what other developers expect when they read your code. This chapter walks through the hierarchy, the attributes every exception carries, and the matching rules except uses.
Prerequisites
This chapter assumes you can:
- Read and write basic Python: functions, classes, and f-strings.
- Use
try,except, andraisein simple cases. - Follow class inheritance, including what a subclass inherits from its parent.
You do not need to have written a custom exception yet. The next chapters cover that.
Exceptions are classes
In Python, an exception is an instance of a class. When you write raise ValueError("bad input"), you create an object of class ValueError and hand it to the interpreter. The interpreter then unwinds the call stack until some except clause accepts that object.
Because exceptions are ordinary classes, they take part in inheritance. An except clause names a class, and it catches an exception if the exception's class is that class or any subclass of it. This rule explains almost everything in this chapter.
You can see the inheritance chain of any exception through its __mro__ attribute (method resolution order, the list of classes Python searches for attributes, starting with the class itself):
for cls in FileNotFoundError.__mro__:
print(cls.__name__)This prints:
FileNotFoundError
OSError
Exception
BaseException
objectFileNotFoundError is a kind of OSError, which is a kind of Exception, which is a kind of BaseException. Every built-in exception follows this pattern.
The shape of the built-in hierarchy
At the top sits BaseException. Every exception class must inherit from it, and Python refuses to raise anything that does not.
Directly below it are a few exceptions that are not errors in the usual sense. They signal that the interpreter or the user wants the program to stop. The rest of the exceptions you meet daily live under Exception.
for name in ("SystemExit", "KeyboardInterrupt", "GeneratorExit", "Exception"):
cls = getattr(__builtins__, name) if hasattr(__builtins__, name) else eval(name)
print(f"{name:18} subclass of Exception? {issubclass(cls, Exception)}")This prints False for the first three names and True for Exception. The __builtins__ lookup above is clumsy. A cleaner version names the classes directly:
for cls in (SystemExit, KeyboardInterrupt, GeneratorExit, Exception):
print(f"{cls.__name__:18} subclass of Exception? {issubclass(cls, Exception)}")The diagram shows the parts of the tree you will use most. It is a selection, not the full list.
Why the split at `Exception` matters
The split between BaseException and Exception exists so that ordinary error handling does not swallow shutdown signals.
| Class | Raised when | Should your code catch it? |
|---|---|---|
| `SystemExit` | `sys.exit()` is called | Rarely. Let it propagate so the program exits. |
| `KeyboardInterrupt` | The user presses Ctrl+C | Rarely. Clean up, then re-raise. |
| `GeneratorExit` | A generator is closed | Almost never. |
| `Exception` and its subclasses | Something went wrong in your program's logic or environment | Yes, as specifically as you can. |
A handler written as except Exception: leaves these three alone, so Ctrl+C still stops the program. A bare except: or except BaseException: catches them, and the program becomes hard to stop. This is why your own exception classes should inherit from Exception, not BaseException.
Families of related errors
Several built-in exceptions exist mainly to group others. Catching the group lets you handle a whole category with one clause.
ArithmeticErrorgroupsZeroDivisionError,OverflowError, andFloatingPointError.LookupErrorgroupsKeyErrorandIndexError. Both mean "the item you asked for is not in this container."OSErrorgroups the operating-system failures:FileNotFoundError,PermissionError,TimeoutError,ConnectionError, and others.ValueErrorandTypeErrorstand on their own. AValueErrormeans the type was right but the value was not. ATypeErrormeans the type itself was wrong.
Here is the grouping rule in action:
def lookup(container, key):
try:
return container[key]
except LookupError as exc:
return f"{type(exc).__name__} caught as LookupError"
print(lookup({"a": 1}, "b"))
print(lookup([1, 2], 5))This prints:
KeyError caught as LookupError
IndexError caught as LookupErrorThe function does not care whether the container is a dictionary or a list. Because both failures share a parent, one handler covers both.
This is the same design you will use for your own package: one base class that lets callers catch every error your code raises, with subclasses for the specific cases. The chapter on hierarchies covers that design in detail.
How `except` matches
When an exception is raised, Python checks the except clauses of the nearest try block from top to bottom. It runs the first clause whose class matches, using the same test as isinstance(exc, SomeClass). It then skips the rest.
Two consequences follow.
First, order matters. Put specific classes before general ones:
def describe(path):
try:
with open(path) as handle:
return handle.read()
except FileNotFoundError:
return "no such file"
except PermissionError:
return "not allowed to read it"
except OSError as exc:
return f"other OS problem: {exc.strerror}"If you moved except OSError to the top, it would match first, because FileNotFoundError is an OSError. The two clauses below it would never run. Python does not warn you about this, so the mistake is silent. Linters such as pylint report it, but the interpreter does not.
Second, you can name several classes in a tuple to share one handler:
try:
value = int(raw_text)
except (ValueError, TypeError):
value = 0If no clause matches, the exception continues up to the caller's try blocks. If it reaches the top of the program, Python prints a traceback and exits with a non-zero status.
What every exception carries
All exceptions inherit a small set of attributes from BaseException. You will use three of them constantly, and the rest of this tutorial builds on them.
`args`
args is a tuple of the arguments passed to the constructor. The default __str__ method is built from it.
err = ValueError("bad port", 99999)
print(err.args)
print(str(err))
single = ValueError("bad port")
print(single.args)
print(str(single))This prints:
('bad port', 99999)
('bad port', 99999)
('bad port',)
bad portWith one argument, str() returns that argument as text. With several, it returns the tuple's text form. With none, it returns an empty string. A later chapter shows how to control this when you add your own fields.
Some built-in classes change the rule. KeyError formats its message with repr, which surprises people:
print(str(KeyError("name")))
print(str(ValueError("name")))This prints 'name' (with quotes) for the first line and name for the second.
`__traceback__`
__traceback__ holds the traceback object, which records the chain of function calls that led to the raise. It is None until the exception is actually raised. Tools such as the traceback module read it to format error reports.
import traceback
def fail():
raise RuntimeError("boom")
try:
fail()
except RuntimeError as exc:
lines = traceback.format_tb(exc.__traceback__)
print(len(lines), "frames recorded")This prints 2 frames recorded, one for the module-level call and one for fail.
`__cause__` and `__context__`
These two attributes link an exception to an earlier one. Python sets __context__ automatically when you raise a new exception while handling another. It sets __cause__ only when you write raise ... from .... Both are None when no earlier exception is involved. The chaining chapter explains the difference and when to use each.
Raising a class and raising an instance
Python lets you raise either a class or an instance:
raise ValueError("port must be between 1 and 65535")
raise ValueErrorThe second form works because Python creates an instance by calling the class with no arguments. Passing a message is almost always better, since an empty exception tells the reader nothing. Raising an instance is also the only way to attach custom data, which later chapters rely on.
Where custom exceptions fit
Your own exception classes join this same tree. A class that inherits from Exception behaves like any built-in one: it has args, a traceback, matching by inheritance, and chaining. You can also inherit from a more specific built-in when it fits. For example, a ConfigValueError(ValueError) is caught by callers who already write except ValueError.
This choice has a cost. A subclass of a built-in inherits that built-in's constructor behavior and its place in every handler that catches the parent. Pick the parent on purpose, based on who should be able to catch it.
Summary of the working model
- Exceptions are classes, and
exceptmatches by inheritance. BaseExceptionis the root, andExceptionis the root for errors you are expected to handle.- Parent classes such as
LookupErrorandOSErrorlet one handler cover a family. - Handlers are tried in order, so list specific classes first.
- Every exception has
args,__traceback__,__cause__, and__context__.
Exercise
What does this code print, and why? Would swapping the order of the two except clauses change the output?
try:
{}["missing"]
except LookupError:
print("first")
except KeyError:
print("second")
Show answer
It prints "first". A KeyError is a subclass of LookupError, so the first clause matches and Python skips the rest. The second clause can never run. Swapping the clauses would print "second", because KeyError would then be tested first and match.
Exercise
A teammate writes except: around a long-running loop to "keep it from crashing". Name one thing that goes wrong when you press Ctrl+C, and give the narrowest fix that still keeps the loop running after ordinary errors.
Show answer
A bare except also catches KeyboardInterrupt (a subclass of BaseException, not Exception), so Ctrl+C is swallowed and the loop keeps running. The fix is to write except Exception:, which catches ordinary errors but lets KeyboardInterrupt and SystemExit propagate. Narrower still, name the specific exceptions the loop body can raise.