Exception Hierarchy
Exception Hierarchy
Python has a well-defined Exception Hierarchy where all exceptions inherit from
the built-in BaseException class.
BaseException
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
└── Exception
├── ArithmeticError
│ ├── ZeroDivisionError
│ ├── FloatingPointError
│ ├── OverflowError
├── LookupError
│ ├── IndexError
│ ├── KeyError
├── OSError
│ ├── FileNotFoundError
│ ├── PermissionError
│ ├── TimeoutError
├── ValueError
├── TypeError
│
├── NameError
│ ├── UnboundLocalError
├── RuntimeError
│ ├── RecursionError
├── AssertionError
├── AttributeError
├── EOFError
├── ImportError
│ ├── ModuleNotFoundError
├── KeyboardInterrupt
├── IndentationError
│ ├── TabError
├── MemoryError
├── NotImplementedError
├── RecursionError
The most common class that all user-defined exceptions inherit from.
x=1/0
except Exception as e:
print("Caught an exception:", e)
Output:
Example: ZeroDivisionError
try:
print(10 / 0)
except ZeroDivisionError:
Example: IndexError
my_list = [1, 2, 3]
try:
except IndexError:
Example: FileNotFoundError
try:
open("non_existent_file.txt", "r")
except FileNotFoundError:
Example: TypeError
try:
print("Hello" + 5)
except TypeError:
Occurs when a function receives an argument of the correct type but invalid value.
Example: ValueError
try:
except ValueError:
Example: ModuleNotFoundError
try:
import non_existent_module
except ModuleNotFoundError:
Example: NameError
try:
print(undefined_variable)
except NameError:
Example: RecursionError
def recursive_function():
return recursive_function()
try:
recursive_function()
except RecursionError:
Key Takeaways