Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to print the Python Exception/Error Hierarchy?
We will learn about what an exception is before learning how to print Python exceptions.
An exception occurs when a program fails to execute in the direction it was intended to be. Python throws exceptions when unexpected errors or events occur during program execution.
Exceptions can be both recoverable and unrecoverable. The exception handling technique can be used when you suspect your code may create an error, preventing the software from crashing.
Following are some common exceptions in Python ?
- IOError (Input Output Error) ? When the file cannot be opened or accessed.
- ImportError ? When Python cannot find or load a module
- ValueError ? Occurs when a function receives an argument of correct type but inappropriate value
- EOFError (End of File Error) ? Caused when the input() encounters an end-of-file condition without reading any data.
Python Exception/Error Hierarchy
Python's exception hierarchy consists of various built-in exceptions organized in a tree structure. This hierarchy uses inheritance concepts where all built-in exceptions are instances of classes derived from BaseException.
This exception hierarchy can be printed using Python's inspect module, which allows you to examine classes, functions, and perform type checking.
Using inspect.getclasstree() Function
The inspect.getclasstree() function displays the hierarchy of exception classes, showing their inheritance relationships.
Syntax
inspect.getclasstree(classes, unique=False)
Example: Displaying BaseException Hierarchy
Here's how to print the complete hierarchy starting from BaseException ?
import inspect
def print_exception_tree(cls, indent=0):
print('-' * indent, cls.__name__)
for subclass in cls.__subclasses__():
print_exception_tree(subclass, indent + 3)
print("Built-in exception hierarchy:")
print_exception_tree(BaseException)
Built-in exception hierarchy: BaseException --- Exception ------ TypeError ------ StopAsyncIteration ------ StopIteration ------ ImportError --------- ModuleNotFoundError ------ OSError --------- FileNotFoundError ------ ValueError ------ RuntimeError ------ NameError ------ AttributeError ------ SyntaxError ------ LookupError --------- IndexError --------- KeyError --- GeneratorExit --- SystemExit --- KeyboardInterrupt
Example: Displaying Exception Hierarchy Only
To display only the Exception class hierarchy (excluding system-level exceptions) ?
import inspect
def print_class_hierarchy(cls, indent=0):
print('.' * indent, cls.__name__)
for subcls in cls.__subclasses__():
print_class_hierarchy(subcls, indent + 3)
print("Exception class hierarchy:")
print_class_hierarchy(Exception)
Exception class hierarchy: Exception ... TypeError ... StopAsyncIteration ... StopIteration ... ImportError ...... ModuleNotFoundError ... OSError ...... FileNotFoundError ... ValueError ... RuntimeError ... NameError ... AttributeError ... SyntaxError ... LookupError ...... IndexError ...... KeyError
Understanding the Hierarchy Structure
| Base Class | Purpose | Common Subclasses |
|---|---|---|
BaseException |
Root of all exceptions | Exception, SystemExit, KeyboardInterrupt |
Exception |
All user-catchable exceptions | ValueError, TypeError, RuntimeError |
LookupError |
Index/key not found errors | IndexError, KeyError |
Practical Exception Handling Example
Here's how understanding the hierarchy helps in exception handling ?
def safe_division(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Cannot divide by zero!")
except TypeError:
print("Please provide numeric values!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Test different scenarios
safe_division(10, 2)
safe_division(10, 0)
safe_division(10, "abc")
Cannot divide by zero! Please provide numeric values!
Conclusion
Understanding Python's exception hierarchy helps you write better error handling code. Use inspect module to explore the hierarchy and catch exceptions at the appropriate level for your application needs.
