How to print the Python Exception/Error Hierarchy? - GeeksforGeeks

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 moduleimport inspect  # our treeClass functiondef 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 calltreeClass(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

Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Python | Pandas dataframe.groupby()
Create a directory in Python