Show the Python exception hierarchy and how catching a base class catches its subclasses.
Every exception in Python descends from BaseException, and almost everything that you will ever catch descends from Exception.
print(issubclass(ValueError, Exception)) # True
print(issubclass(KeyError, LookupError)) # True
print(issubclass(LookupError, Exception)) # True
print(issubclass(KeyboardInterrupt, Exception)) # False
# Catching the base class catches the subclass.
try:
raise KeyError('missing')
except LookupError as error:
print('LookupError caught:', type(error).__name__)
The LookupError clause catches a KeyError, because KeyError inherits from LookupError. That is the whole mechanism. An except clause names a class, and it catches that class together with everything below it in the tree.
There are a few subtrees worth knowing. Under Exception sits ArithmeticError, which covers ZeroDivisionError, OverflowError, and FloatingPointError. LookupError covers KeyError, IndexError, and AttributeError. And OSError covers FileNotFoundError, PermissionError, TimeoutError, and the rest of the file and network errors. Catching LookupError is often the right level when you want to handle any kind of lookup failure without caring which one it was.
The last line of the output is the one to notice. KeyboardInterrupt is not a subclass of Exception, so an except Exception clause will not catch it. It comes straight from BaseException, along with SystemExit and GeneratorExit. Those three are signals that control the flow of a program rather than errors that a program made.