Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to print the Python Exception/Error Hierarchy?

I am new to Python programming and I am learning exception handling. Is there any command or code snippet in python to print the Exception/Error Class hierarchy?

 The output should on the lines of the following: https://docs.python.org/2/library/exceptions.html#exception-hierarchy


1 Answer
Rajendra Dharmkar

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.

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)

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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.