How to print the Python Exception/Error Hierarchy?

PythonServer Side ProgrammingProgramming

We import the inspect module and specifically use the getclasstree() function to print the python Exception/Error hierarchy.

This code arranges and prints the given list of exception classes into a hierarchy of nested lists. We recursively go through __subclasses__() down by an inheritance tree as shown in the output.

Example

import inspect
print "The class hierarchy for built-in exceptions is:"
inspect.getclasstree(inspect.getmro(BaseException))
def classtree(cls, indent=0):
print '.' * indent, cls.__name__
for subcls in cls.__subclasses__():
classtree(subcls, indent + 3)
classtree(BaseException)

Output

On running the code we get the following output.

The class hierarchy for built-in exceptions is:
BaseException
... Exception
...... StandardError
......... TypeError
......... ImportError
............ ZipImportError
......... EnvironmentError
............ IOError
............ OSError
............... WindowsError
......... EOFError
......... RuntimeError
............ NotImplementedError
......... NameError
............ UnboundLocalError
......... AttributeError
......... SyntaxError
............ IndentationError
............... TabError
......... LookupError
............ IndexError
............ KeyError
............ CodecRegistryError
......... ValueError
............ UnicodeError
............... UnicodeEncodeError
............... UnicodeDecodeError
............... UnicodeTranslateError
......... AssertionError
......... ArithmeticError
............ FloatingPointError
............ OverflowError
............ ZeroDivisionError
......... SystemError
............ CodecRegistryError
......... ReferenceError
......... MemoryError
......... BufferError
...... StopIteration
...... Warning
......... UserWarning
......... DeprecationWarning
......... PendingDeprecationWarning
......... SyntaxWarning
......... RuntimeWarning
......... FutureWarning
......... ImportWarning
......... UnicodeWarning
......... BytesWarning
...... _OptionError
...... error
...... Error
...... TokenError
...... StopTokenizing
...... error
...... EndOfBlock
... GeneratorExit
... SystemExit
... KeyboardInterrupt
raja
Published on 07-Dec-2017 07:06:35
Advertisements