The Exception Hierarchy
Learn about the exception hierarchy in Python.
We'll cover the following
We’ve already seen several of the most common built-in exceptions, and we’ll probably encounter the rest over the course of our regular Python development.
As we noticed earlier, most exceptions are subclasses of the Exception
class.
But this is not true of all exceptions. The Exception
class actually extends a class called BaseException
. In fact, all exceptions must extend the BaseException
class or one of its subclasses.
Types of BaseException
There are two key built-in exception classes:
SystemExit
KeyboardInterrupt
The later one derive directly from the BaseException
class instead of the Exception
class.
The SystemExit
class
The SystemExit
exception is raised whenever the program exits naturally, typically because we called the sys.exit()
function somewhere in our code. For example, when the user selected an exit menu item, clicked the Close button on a window, entered a command to shut down a server, or the OS sent a signal to the application to terminate.
This exception is designed to allow us to clean up code before the program ultimately exits.
If we do handle the SystemExit
exception, we would normally re-raise the exception, since catching it could stop the program from exiting. Imagine a web service with a bug that is holding database locks and can’t be stopped without rebooting the server.
The KeyboardInterrupt
class
We don’t want a SystemExit
exception to be accidentally caught in generic except Exception:
clauses. This is why it derives directly from BaseException
.
The KeyboardInterrupt
exception is common in command-line programs. It is thrown when the user explicitly interrupts program execution with an OS-dependent key combination (normally, Ctrl + C
). For Linux and macOS users, the kill -2 <pid>
command will also work. This is a standard way for the user to deliberately interrupt a running program and, like the SystemExit
exception, it should almost always respond by terminating the program. Also, like SystemExit
, it can handle any cleanup tasks inside the finally
blocks.
Here is a class diagram that fully illustrates the hierarchy:
Get hands-on with 1400+ tech skills courses.