Exceptions help your program handle errors without crashing. The exception hierarchy shows how different errors are related, making it easier to catch and fix them.
0
0
Exception hierarchy in Python
Introduction
When you want to catch all errors of a certain type or group.
When you create your own error types to organize problems clearly.
When you want to handle specific errors differently but still catch general errors.
When debugging to understand what kind of error happened.
When writing code that needs to be safe and not stop unexpectedly.
Syntax
Python
BaseException
├── SystemExit
├── KeyboardInterrupt
├── Exception
├── ArithmeticError
├── LookupError
├── ... (other built-in exceptions)
The top of the hierarchy is BaseException, which is the parent of all errors.
Most user errors come from Exception, which is a child of BaseException.
Examples
This catches a specific error: dividing by zero.
Python
try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
This catches an error when converting a string to a number fails.
Python
try: x = int('abc') except ValueError: print("Invalid number!")
This catches any error that is a child of
Exception, including ZeroDivisionError.Python
try: x = 1 / 0 except Exception: print("Some error happened")
Sample Program
This program shows how different exceptions from the hierarchy are caught separately or generally.
Python
def test_errors(value): try: if value == 'zero': result = 1 / 0 elif value == 'key': raise KeyError('missing key') else: result = int(value) print(f'Result is {result}') except ZeroDivisionError: print('Caught a ZeroDivisionError') except KeyError: print('Caught a KeyError') except Exception: print('Caught a general exception') print('Test with zero:') test_errors('zero') print('Test with key:') test_errors('key') print('Test with invalid int:') test_errors('abc') print('Test with valid int:') test_errors('10')
OutputSuccess
Important Notes
Always catch specific exceptions before general ones to avoid hiding errors.
Use Exception to catch most errors, but avoid catching BaseException unless you really want to catch system-exiting events.
You can create your own exceptions by inheriting from Exception or its children.
Summary
Exceptions are organized in a tree called the exception hierarchy.
Catching exceptions from higher in the hierarchy catches more errors.
Use specific exceptions to handle errors clearly and safely.