Sub topic 1
How Python exceptions are organized
Every exception in Python is an object, and every exception class sits in one inheritance tree. This chapter shows the shape of that tree. A custom exception only makes sense once you know where it will sit.
Prerequisites
You should be comfortable with these before reading on:
- Basic Python syntax, functions, and classes.
- Using
try,except, andraise. - Class inheritance and calling
super().__init__.
The tree starts at BaseException
All exceptions inherit from BaseException. Most of the ones you handle in everyday code inherit from its subclass Exception. The few that don't signal that the interpreter or the user wants the program to stop:
SystemExit, raised bysys.exit().KeyboardInterrupt, raised when the user presses Ctrl+C.GeneratorExit, raised inside a generator when it is closed.
You can read the chain for any class from its method resolution order, __mro__:
print([cls.__name__ for cls in KeyError.__mro__])The output is ['KeyError', 'LookupError', 'Exception', 'BaseException', 'object']. Python checks this chain from left to right when it decides whether a handler matches.
An except clause matches subclasses
except SomeClass catches SomeClass and every class derived from it. That is why a parent class works as a group name:
data = {"a": 1}
try:
data["b"]
except LookupError as exc:
print(type(exc).__name__, exc)This prints KeyError 'b'. The handler names LookupError, but the object is a KeyError. The same code would also catch an IndexError from a list. Your own exceptions get this behavior for free. A handler for a base class you define will catch all of its subclasses, which the later chapters on hierarchies build on.
Order your handlers from specific to general
Python runs the first except clause that matches. If a general class comes first, it hides the specific ones after it:
try:
open("missing.txt")
except FileNotFoundError:
print("file is not there")
except OSError:
print("some other operating system problem")FileNotFoundError is a subclass of OSError. If you swapped the two clauses, the OSError handler would catch every case and the FileNotFoundError handler would never run.
Why most code catches Exception, not BaseException
Catching Exception handles ordinary program errors and lets exit signals pass through. Catching BaseException, or writing a bare except:, also catches KeyboardInterrupt and SystemExit. The program then can't be stopped with Ctrl+C.
def risky():
raise ValueError("bad input")
try:
risky()
except Exception as exc:
print("handled:", exc)This is also why custom exceptions should inherit from Exception. Callers who write except Exception will then see your errors, and they won't accidentally swallow exit signals.
Common errors
- Bare
except:. It catches everything, includingKeyboardInterrupt. Name a class, or useexcept Exception. - Wrong handler order. A parent class listed before its child makes the child's handler dead code.
- Assuming
Exceptionis the root. It is not.BaseExceptionis, and a few exit-related classes sit outsideException. - Matching on message text. Match on class. The class is the part of an exception that is meant to be stable.
Exercise
Given except OSError: followed by except FileNotFoundError: in the same try statement, which handler runs when open("missing.txt") fails, and why?
Show answer
The OSError handler runs. FileNotFoundError is a subclass of OSError, so the first clause matches, and Python runs only the first matching clause. The FileNotFoundError handler can never run. Put the specific class first.
Exercise
What does [c.__name__ for c in ZeroDivisionError.__mro__] show, and which built-in class can you name in an except clause to catch both ZeroDivisionError and OverflowError?
Show answer
It shows ['ZeroDivisionError', 'ArithmeticError', 'Exception', 'BaseException', 'object']. ArithmeticError is the shared parent of both, so except ArithmeticError catches both.