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 Let's start by looking at the full Python exception class hierarchy, as seen below: 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. 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: 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 Yet, as we see in the hierarchy above, Python merely inherits from The The This class also includes a The A This simple exception is raised when the user presses a key combination that causes an Finally, the 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!
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.
Major Exception Types Overview
exception in the
Exception parent classes, and the use of
error in most subclasses therein. Most other languages, such as .NET or Java, explicitly differentiate between
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.
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.
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.
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.
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 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
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
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
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
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
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.
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.
interrupt to the executing script. For example, many terminals accept
Ctrl+C as an interrupt keystroke.
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.
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
Let's start by looking at the full Python exception class hierarchy, as seen below:
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.
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:
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
Yet, as we see in the hierarchy above, Python merely inherits from
This class also includes a
This simple exception is raised when the user presses a key combination that causes an
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
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? ›
- ArithmeticError. FloatingPointError. OverflowError. ZeroDivisionError.
- ImportError. ModuleNotFoundError.
- LookupError. IndexError. KeyError.
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? ›
- Step 1: Convert the data to Dataframe,
- Step 2: Take a unique element from column 1 which is not in column 2,
- Step 3: After taking the unique element from column 1, Convert column 1 as Dataframe,
- Step 4: Merge the Dataframes, by using pd. ...
- Step 5: Drop_duplicates by all columns.
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.
|EOFError||Raised when the input() function hits the end-of-file condition.|
|FloatingPointError||Raised when a floating point operation fails.|
|GeneratorExit||Raised when a generator's close() method is called.|
|ImportError||Raised when the imported module is not found.|
|Exception||Cause of Error|
|SyntaxError||Raised by parser when syntax error is encountered.|
|IndentationError||Raised when there is incorrect indentation.|
|TabError||Raised when indentation consists of inconsistent tabs and spaces.|
|SystemError||Raised when interpreter detects internal error.|
- 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.
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.
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.
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? ›
- Single Inheritance.
- Multiple Inheritance.
- Multilevel Inheritance.
- Hierarchical Inheritance.
- Hybrid Inheritance.
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.
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.
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.