How to print the Python Exception/Error Hierarchy?
Last Updated :
20 Aug, 2020
Before Printing the Error Hierarchy let's understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Built-in Exceptions in Python let's try to print them out in a hierarchy.
For printing the tree hierarchy we will use inspect module in Python. The inspect module provides useful functions to get information about objects such as modules, classes, methods, functions, and code objects. For example, it can help you examine the contents of a class, extract and format the argument list for a function.
For building a tree hierarchy we will use inspect.getclasstree().
Syntax: inspect.getclasstree(classes, unique=False)
inspect.getclasstree() arranges the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list.
If the unique argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.
Let's write a code for printing tree hierarchy for built-in exceptions:
Python3
# import inspect module
import inspect
# our treeClass function
def treeClass(cls, ind = 0):
# print name of the class
print ('-' * ind, cls.__name__)
# iterating through subclasses
for i in cls.__subclasses__():
treeClass(i, ind + 3)
print("Hierarchy for Built-in exceptions is : ")
# inspect.getmro() Return a tuple
# of class cls’s base classes.
# building a tree hierarchy
inspect.getclasstree(inspect.getmro(BaseException))
# function call
treeClass(BaseException)
Output:
Hierarchy for Built-in exceptions is :
BaseException
--- Exception
------ TypeError
------ StopAsyncIteration
------ StopIteration
------ ImportError
--------- ModuleNotFoundError
--------- ZipImportError
------ OSError
--------- ConnectionError
------------ BrokenPipeError
------------ ConnectionAbortedError
------------ ConnectionRefusedError
------------ ConnectionResetError
--------- BlockingIOError
--------- ChildProcessError
--------- FileExistsError
--------- FileNotFoundError
--------- IsADirectoryError
--------- NotADirectoryError
--------- InterruptedError
--------- PermissionError
--------- ProcessLookupError
--------- TimeoutError
--------- UnsupportedOperation
------ EOFError
------ RuntimeError
--------- RecursionError
--------- NotImplementedError
--------- _DeadlockError
------ NameError
--------- UnboundLocalError
------ AttributeError
------ SyntaxError
--------- IndentationError
------------ TabError
------ LookupError
--------- IndexError
--------- KeyError
--------- CodecRegistryError
------ ValueError
--------- UnicodeError
------------ UnicodeEncodeError
------------ UnicodeDecodeError
------------ UnicodeTranslateError
--------- UnsupportedOperation
------ AssertionError
------ ArithmeticError
--------- FloatingPointError
--------- OverflowError
--------- ZeroDivisionError
------ SystemError
--------- CodecRegistryError
------ ReferenceError
------ MemoryError
------ BufferError
------ Warning
--------- UserWarning
--------- DeprecationWarning
--------- PendingDeprecationWarning
--------- SyntaxWarning
--------- RuntimeWarning
--------- FutureWarning
--------- ImportWarning
--------- UnicodeWarning
--------- BytesWarning
--------- ResourceWarning
------ _OptionError
------ error
------ Verbose
------ Error
------ TokenError
------ StopTokenizing
------ EndOfBlock
--- GeneratorExit
--- SystemExit
--- KeyboardInterrupt
Similar Reads
How to Print Exception Stack Trace in Python In Python, when an exception occurs, a stack trace provides details about the error, including the function call sequence, exact line and exception type. This helps in debugging and identifying issues quickly.Key Elements of a Stack Trace:Traceback of the most recent callLocation in the programLine
3 min read
Handling EOFError Exception in Python In Python, an EOFError is raised when one of the built-in functions, such as input() or raw_input() reaches the end-of-file (EOF) condition without reading any data. This commonly occurs in online IDEs or when reading from a file where there is no more data left to read. Example:Pythonn = int(input(
4 min read
How to log a Python exception? To log an exception in Python we can use a logging module and through that, we can log the error. The logging module provides a set of functions for simple logging and the following purposes DEBUGINFOWARNINGERRORCRITICALLog a Python Exception Examples Example 1:Logging an exception in Python with an
2 min read
How to handle KeyError Exception in Python In this article, we will learn how to handle KeyError exceptions in Python programming language. What are Exceptions?It is an unwanted event, which occurs during the execution of the program and actually halts the normal flow of execution of the instructions.Exceptions are runtime errors because, th
3 min read
How To Fix Valueerror Exceptions In Python Python comes with built-in exceptions that are raised when common errors occur. These predefined exceptions provide an advantage because you can use the try-except block in Python to handle them beforehand. For instance, you can utilize the try-except block to manage the ValueError exception in Pyth
4 min read
How to pass argument to an Exception in Python? There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the fol
2 min read