









Python Exceptions
What Are Python Exceptions?
In Python, an exception is an error that disrupts the normal flow of a program. When something goes wrong during execution—like dividing by zero or trying to access an index that doesn’t exist—Python stops and raises an exception.
Knowing how and why they occur is the first step in building resilient, bug-free Python applications. Later, you'll learn how to catch and handle them, but first, we must learn to recognize them.
When Does Python Raise an Exception?
Python raises an exception during runtime when it encounters an issue that it doesn’t know how to handle. This stops the execution of the program and displays an error message (also called a traceback).
Basic Example: Division by Zero
x = 5
y = 0
result = x / y
print(result)
Traceback (most recent call last):
File "main.py", line 3, in <module>
result = x / y
ZeroDivisionError: division by zero
Python gives us a traceback—a report of where the error occurred. In this case, it tells us exactly which line failed and what kind of error it was: ZeroDivisionError
.
Another Example: Accessing a Non-Existent Index
fruits = ["apple", "banana", "cherry"]
print(fruits[5])
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(fruits[5])
IndexError: list index out of range
Here, the list only has 3 elements, indexed 0 through 2. Trying to access index 5 raises an IndexError
.
Common Built-in Exceptions in Python
Exception | Description |
---|---|
ZeroDivisionError | Raised when dividing by zero |
TypeError | Raised when an operation is applied to an object of inappropriate type |
NameError | Raised when a variable is not defined |
IndexError | Raised when a sequence index is out of range |
KeyError | Raised when a dictionary key isn’t found |
ValueError | Raised when a function receives an argument of right type but inappropriate value |
AttributeError | Raised when an invalid attribute reference is made |
ImportError | Raised when a module or name cannot be found during import |
Best Practices for Beginners
- Don’t ignore exceptions; read and understand them.
- Use print statements or debugging tools to inspect values before failure points.
- Always know the type and shape of your data before using it.
- Refer to the traceback line numbers to locate and fix errors quickly.
Summary
Python exceptions are runtime errors that occur when something goes wrong while executing your code. In the next section, we’ll explore how to catch and handle these exceptions using try
and except
.