The Python Exception Class Hierarchy (2023)

The Python exception class hierarchy consists of a few dozen different exceptions spread across a handful of important base class types. As with most programming languages, errors occur within a Python application when something unexpected goes wrong. Anything from improper arithmetic and running out of memory to invalid file references and unicode formatting errors may be raised by Python under certain circumstances.

Most of the errors we'll explore in this series are considered exceptions, which indicate that these are non-fatal errors. While a fatal error will halt execution of the current application, all non-fatal exceptions allow execution to continue. This allows our code to explicitly catch or rescue the raised exception and programmatically react to it in an appropriate manner.

Let's start by looking at the full Python exception class hierarchy, as seen below:

  • BaseException
    • Exception
      • ArithmeticError
        • FloatingPointError
        • OverflowError
        • ZeroDivisionError
      • AssertionError
      • AttributeError
      • BufferError
      • EOFError
      • ImportError
        • ModuleNotFoundError
      • LookupError
        • IndexError
        • KeyError
      • MemoryError
      • NameError
        • UnboundLocalError
      • OSError
        • BlockingIOError
        • ChildProcessError
        • ConnectionError
          • BrokenPipeError
          • ConnectionAbortedError
          • ConnectionRefusedError
          • ConnectionResetError
        • FileExistsError
        • FileNotFoundError
        • InterruptedError
        • IsADirectoryError
        • NotADirectoryError
        • PermissionError
        • ProcessLookupError
        • TimeoutError
      • ReferenceError
      • RuntimeError
        • NotImplementedError
        • RecursionError
      • StopIteration
      • StopAsyncIteration
      • SyntaxError
        • IndentationError
          • TabError
      • SystemError
      • TypeError
      • ValueError
        • UnicodeError
          • UnicodeDecodeError
          • UnicodeEncodeError
          • UnicodeTranslateError
      • Warning
        • BytesWarning
        • DeprecationWarning
        • FutureWarning
        • ImportWarning
        • PendingDeprecationWarning
        • ResourceWarning
        • RuntimeWarning
        • SyntaxWarning
        • UnicodeWarning
        • UserWarning
    • GeneratorExit
    • KeyboardInterrupt
    • SystemExit

As we publish future exception-specific articles in this series we'll update the full list above to relevant tutorial and article links for each exception, so this post can act as a go-to resource for Python exception handling tips.

Major Exception Types Overview

Next, let's briefly discuss each important top-level exception type. These top-level exceptions will serve as a basis for digging into specific exceptions in future articles. Before we do that, however, it's worth pointing out what might appear as a slight discrepancy when looking over the list of exception classes provided in Python. To illustrate, look closely at this small snippet of the Python exception class hierarchy and see if anything slightly strange pops out to you:

  • BaseException
    • Exception
      • ArithmeticError
        • FloatingPointError
        • OverflowError
        • ZeroDivisionError
      • AssertionError

For developers that have worked with other programming languages in the past, what you might take note of is the distinction between using the word exception in the BaseException and Exception parent classes, and the use of error in most subclasses therein. Most other languages, such as .NET or Java, explicitly differentiate between exceptions and errors by separating them into distinct categories. In such languages, errors typically denote fatal errors (those that crash the application), whereas exceptions are catchable/rescuable errors.

Yet, as we see in the hierarchy above, Python merely inherits from Exception with a series of XYZError classes. The reason for this naming convention comes from the PEP8 Python style guide, which makes an explicit mention that "you should use the suffix 'Error' on your exception names (if the exception is actually an error)." I've added the extra emphasis to that quote, because the latter point is critical here -- most Python exceptions with Error in the name are, in fact, errors.


The BaseException class is, as the name suggests, the base class for all built-in exceptions in Python. Typically, this exception is never raised on its own, and should instead be inherited by other, lesser exception classes that can be raised.

The BaseException class (and, thus, all subclass exceptions as well) allows a tuple of arguments to be passed when creating a new instance of the class. In most cases, a single argument will be passed to an exception, which is a string value indicating the specific error message.

This class also includes a with_traceback(tb) method, which explicitly sets the new traceback information to the tb argument that was passed to it.


Exception is the most commonly-inherited exception type (outside of the true base class of BaseException). In addition, all exception classes that are considered errors are subclasses of the Exception class. In general, any custom exception class you create in your own code should inherit from Exception.

The Exception class contains many direct child subclasses that handle most Python errors, so we'll briefly go over each below:

  • ArithmeticError - The base class for the variety of arithmetic errors, such as when attempting to divide by zero, or when an arithmetic result would be too large for Python to accurately represent.
  • AssertionError - This error is raised when a call to the [assert] statement fails.
  • AttributeError - Python's syntax includes something called attribute references, which is just the Python way of describing what you might know of as dot notation. In essence, any primary token in Python (like an identifier, literal, and so forth) can be written and followed by a period (.), which is then followed by an identifier. That syntax (i.e. primary.identifier) is called an attribute reference, and anytime the executing script encounters an error in such syntax an AttributeError is raised.
  • BufferError - Python allows applications to access low level memory streams in the form of a buffer. For example, the bytes class can be used to directly work with bytes of information via a memory buffer. When something goes wrong within such a buffer operation a BufferError is raised.
  • EOFError - Similar to the Java EOFException article we did a few days ago, Python's EOFError is raised when using the input() function and reaching the end of a file without any data.
  • ImportError - Modules are usually loaded in memory for Python scripts to use via the import statement (e.g. import car from vehicles). However, if an import attempt fails an ImportError will often be raised.
  • LookupError - Like ArithmeticError, the LookupError is generally considered a base class from which other subclasses should inherit. All LookupError subclasses deal with improper calls to a collection are made by using invalid key or index values.
  • MemoryError - In the event that your Python application is about to run out of memory a MemoryError will be raised. Since Python is smart enough to detect this potential issue slightly before all memory is used up, a MemoryError can be rescued and allow you to recover from the situation by performing garbage collection of some kind.
  • NameError - Raised when trying to use an identifier with an invalid or unknown name.
  • OSError - This error is raised when a system-level problem occurs, such as failing to find a local file on disk or running out of disk space entirely. OSError is a parent class to many subclasses explicitly used for certain issues related to operating system failure, so we'll explore those in future publications.
  • ReferenceError - Python includes the weakref module, which allows Python code to create a specific type of reference known as a weak reference. A weak reference is a reference that is not "strong" enough to keep the referenced object alive. This means that the next cycle of garbage collection will identify the weakly referenced object as no longer strongly referenced by another object, causing the weakly referenced object to be destroyed to free up resources. If a weak reference proxy created via the weakref.proxy() function is used after the object that is referenced has already been destroyed via garbage collection, a ReferenceError will be raised.
  • RuntimeError - A RuntimeError is typically used as a catchall for when an error occurs that doesn't really fit into any other specific error classification.
  • StopIteration - If no default value is passed to the next() function when iterating over a collection, and that collection has no more iterated value to retrieve, a StopIteration exception is raised. Note that this is not classified as an Error, since it doesn't mean that an error has occurred.
  • StopAsyncIteration - As of version 3.5, Python now includes coroutines for asynchronous transactions using the async and await syntax. As part of this feature, collections can be asynchronously iterated using the __anext__() method. The __anext__() method requires that a StopAsyncIteration instance be raised in order to halt async iteration.
  • SyntaxError - Just like most programming languages, a SyntaxError in Python indicates that there is some improper syntax somewhere in your script file. A SyntaxError can be raised directly from an executing script, or produced via functions like eval() and exec().
  • SystemError - A generic error that is raised when something goes wrong with the Python interpreter (not to be confused with the OSError, which handles operating system issues).
  • TypeError - This error is raised when attempting to perform an operation on an incorrect object type.
  • ValueError - Should be raised when a function or method receives an argument of the correct type, but with an actual value that is invalid for some reason.
  • Warning - Another parent class to many subclasses, the Warning class is used to alert the user in non-dire situations. There are a number of subclass warnings that we'll explore in future articles.


A generator is a specific type of iterator in Python, which simplifies the process of creating iterators with constantly changing values. By using the yield statement within a generator code block, Python will return or "generate" a new value for each call to next(). When the explicit generator.close() method is called a GeneratorExit instance is raised.


This simple exception is raised when the user presses a key combination that causes an interrupt to the executing script. For example, many terminals accept Ctrl+C as an interrupt keystroke.


Finally, the SystemExit exception is raised when calling the sys.exit() method, which explicitly closes down the executing script and exits Python. Since this is an exception, it can be rescued and programmatically responded to immediately before the script actually shuts down.

That's just a small taste of the powerful, built-in Python exception class hierarchy as of version 3.6. Stay tuned for more in-depth articles examining each of these exceptions in greater detail, and be sure to check out Airbrake's robust error monitoring software, which provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake's state of the art web dashboard ensures you receive round-the-clock status updates on your application's health and error rates. No matter what you're working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize exception parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.

Check out Airbrake's error monitoring software today with a 14-day trial and see for yourself why so many of the world's best engineering teams use Airbrake to revolutionize their exception handling practices!

Written By: Frances Banks


What is the hierarchy of Python exceptions? ›

According to the exception hierarchy of Python 2, we can identify the three main types of Python exceptions, such as StopIteration, StandardError, and Warning.

How exception is handled in Python hierarchy? ›

Exception handling occurs based on an exception hierarchy, determined by the inheritance structure of the exception classes. For example, IOError and OSError are both subclasses of EnvironmentError . Code that catches an IOError will not catch an OSError .

What are the 3 major exception types in Python? ›

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.

Which classes are the exception classes in Python? ›

Python Exception Base Classes
  • ArithmeticError. FloatingPointError. OverflowError. ZeroDivisionError.
  • AssertionError.
  • AttributeError.
  • BufferError.
  • EOFError.
  • ImportError. ModuleNotFoundError.
  • LookupError. IndexError. KeyError.
  • MemoryError.
Jun 25, 2020

What is the hierarchy of exception class? ›

The hierarchy of Exceptions in the Java programming language begins with the Throwable class – which comes from the Object class and is its direct subclasswhileThe Exception class presents all This Throwable class further branches into two subclasses – Error and Exception.

What is class hierarchy in Python? ›

The class from which a class inherits is called the parent or superclass. A class which inherits from a superclass is called a subclass, also called heir class or child class. Superclasses are sometimes called ancestors as well. There exists a hierarchical relationship between classes.

How do you use hierarchy in Python? ›

With Simple Steps, we can do this,
  1. Step 1: Convert the data to Dataframe,
  2. Step 2: Take a unique element from column 1 which is not in column 2,
  3. Step 3: After taking the unique element from column 1, Convert column 1 as Dataframe,
  4. Step 4: Merge the Dataframes, by using pd. ...
  5. Step 5: Drop_duplicates by all columns.
May 29, 2017

What is hierarchical inheritance in Python with example? ›

Hierarchical Inheritance If multiple derived classes are created from the same base, this kind of Inheritance is known as hierarchical inheritance. In this instance, we have two base classes as a parent (base) class as well as two children (derived) classes.

How does Python handle exception handling? ›

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.

What is the main class of exception? ›

The Exception class has two main subclasses: IOException class and RuntimeException Class.

What are the important exceptions in Python? ›

Python - Error Types
EOFErrorRaised when the input() function hits the end-of-file condition.
FloatingPointErrorRaised when a floating point operation fails.
GeneratorExitRaised when a generator's close() method is called.
ImportErrorRaised when the imported module is not found.
26 more rows

How many types of exceptions are there in Python? ›

Python Built-in Exceptions
ExceptionCause of Error
SyntaxErrorRaised by parser when syntax error is encountered.
IndentationErrorRaised when there is incorrect indentation.
TabErrorRaised when indentation consists of inconsistent tabs and spaces.
SystemErrorRaised when interpreter detects internal error.
26 more rows

What are the three major types of exception classes? ›

Java exceptions can be broken down into one of three categories:
  • Checked - these are exceptions that are checked by the compiler at compile time. ...
  • Error - errors are exceptions that happen externally to your Java program. ...
  • Runtime - runtime exceptions are internal to your application but are not typically recoverable.
Jul 19, 2021

What are the exception class functions? ›

An exception is an object that describes an error or unexpected behaviour of a PHP script. Exceptions are thrown by many PHP functions and classes. User defined functions and classes can also throw exceptions. Exceptions are a good way to stop a function when it comes across data that it cannot use.

Which is the class hierarchy? ›

A class hierarchy or inheritance tree in computer science is a classification of object types, denoting objects as the instantiations of classes (class is like a blueprint, the object is what is built from that blueprint) inter-relating the various classes by relationships such as "inherits", "extends", "is an ...

What is class hierarchy give example in OOPs? ›

3.1 OOP: Class Hierarchy. In object-oriented programming, a class is a template that defines the state and behavior common to objects of a certain kind. A class can be defined in terms of other classes. For example, a truck and a racing car are both examples of a car.

What is hierarchy in exception handling? ›

Exception Handling: The process of dealing with exceptions is known as Exception Handling. Hierarchy of Exceptions: Object class is the parent class of all the classes of java and all the errors or Exceptions objects inherited by throwable class. The throwable class has two subclass Errors and Exception.

What does a class hierarchy do? ›

What does a class hierarchy depict? It shows the relationships between the classes in the form of an organization chart.

What is a hierarchy and examples? ›

A hierarchy (from Greek: ἱεραρχία, hierarkhia, 'rule of a high priest', from hierarkhes, 'president of sacred rites') is an arrangement of items (objects, names, values, categories, etc.) that are represented as being "above", "below", or "at the same level as" one another.

How many types of hierarchy are there? ›

If you are looking for a new career prospect or if you are starting to find your way in the industry, you might come across specific questions. These questions are the factors that tell what your expectations from the job provider are.

Why are hierarchies useful? ›

The basic function of a hierarchy is to allow us to make sense of the world, simplify information, and make decisions. Think of it in an evolutionary sense: Back in prehistoric days, when someone said, “Throw the spear now to take down the mammoth,” it was essential to recognize their leadership.

What is an example of a hierarchy of data? ›

Examples of the hierarchical data that is commonly stored in databases include the following: An organizational structure. A file system. A set of tasks in a project.

Why is hierarchical important? ›

Hierarchy creates authority and unity

An employee's level of authority is greater the higher they are in the hierarchical structure. Wherever leadership is required, authority is also needed. Authority ensures that everyone under a manager's command will work towards the organisation's goals — or face discipline.

What is correct for a hierarchical inheritance? ›

Hierarchical Inheritance in C++ refers to the type of inheritance that has a hierarchical structure of classes. A single base class can have multiple derived classes, and other subclasses can further inherit these derived classes, forming a hierarchy of classes.

What are the four 4 classification types of inheritance? ›

Explore 5 Types of Inheritance in C++ With Examples
  • Single Inheritance.
  • Multiple Inheritance.
  • Multilevel Inheritance.
  • Hierarchical Inheritance.
  • Hybrid Inheritance.
Nov 22, 2022

Is hierarchical inheritance possible in Python? ›

The new derived class is called the child class and the existing class is called the parent class. Hierarchical inheritance in python, Multilevel inheritance in python including Single and Multiple inheritances are the types of inheritance.

How do you pass exceptions in Python? ›

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

What are the two key words Python uses for handling errors? ›

Python uses try and except keywords to handle exceptions. Both keywords are followed by indented blocks. The try: block contains one or more statements which are likely to encounter an exception.

How does Python handle multiple exceptions? ›

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

Which is the top of the exception class hierarchy? ›

The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses - Exception and Error.

Which exception has highest priority? ›

This means that the Reset, HardFault, and NMI exceptions, with fixed negative priority values, always have higher priority than any other exception.

How do you use exception class? ›

To create the exception object, the program uses the throw keyword followed by the instantiation of the exception object. At runtime, the throw clause will terminate execution of the method and pass the exception to the calling method.

What is the correct order of precedence in Python? ›

Answer: The correct order of precedence is given by PEMDAS which means Parenthesis (), Exponential **, Multiplication *, Division /, Addition +, Subtraction -.

What is the order of inheritance in Python? ›

This is left-to-right, depth-first. So, in the above class, the search order will be – Child, Mother, Father, Object. This order is called linearization of class Child, and the set of rules applied are called MRO (Method Resolution Order).

How exceptions are raised in Python? ›

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

What are the 3 rules of precedence? ›

In other words, the precedence is: Parentheses (simplify inside 'em) Exponents (apply them) Multiplication and Division (going from left to right)

What is the order of precedence highest? ›

Explanation: Operator ++ has the highest precedence than / , * and +.

Which operation has the highest order of precedence? ›

The operator precedence is responsible for evaluating the expressions. In Java, parentheses() and Array subscript[] have the highest precedence in Java. For example, Addition and Subtraction have higher precedence than the Left shift and Right shift operators.

Is Priority 1 the highest priority? ›

There are good reasons for setting 1 (or 0) as the highest level of priority and using higher numbers for lower priorities. First, the priority can represent the order that task(s) should be performed. Number 1 is the first task you do, hence it has higher priority than the second set of tasks you will perform.

Which selector has higher priority? ›

Id selector has highest priority because of unique nature of the ID attribute definition. We have two classes with one ID selector here it will apply font-size:12px and font-weight:500 due to the specificity rule as ID selector has highest priority after inline CSS.

Does class order matter in Python? ›

It doesn't matter what order they are given in the parameter so long as the arguments in the call expression match the correct variable. Either way won't matter to the output string.


Top Articles
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated: 11/15/2023

Views: 6311

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.