Common Python Errors and Example Programs
In Python, there are several common built-in exceptions that every developer should understand. Here we will demonstrate 1 example for each kind of error, with detailed explanation.
1. ZeroDivisionError
error_zero_division.py
try:
a = 10
b = 0
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero!")
output.txt
Cannot divide by zero!
2. ValueError
error_value.py
try:
num = int("abc")
except ValueError:
print("Invalid value: cannot convert string to integer.")
output.txt
Invalid value: cannot convert string to integer.
3. IndexError
error_index.py
try:
lst = [10, 20, 30]
print(lst[5])
except IndexError:
print("List index out of range!")
output.txt
List index out of range!
4. KeyError
error_key.py
try:
d = {"name": "Alice"}
print(d["age"])
except KeyError:
print("Key not found in dictionary!")
output.txt
Key not found in dictionary!
5. TypeError
error_type.py
try:
result = "abc" + 5
except TypeError:
print("Cannot add string and integer!")
output.txt
Cannot add string and integer!
6. FileNotFoundError
error_file_not_found.py
try:
file = open("nonexistent_file.txt", "r")
except FileNotFoundError:
print("File not found!")
output.txt
File not found!
7. AttributeError
error_attribute.py
try:
x = 10
x.append(5)
except AttributeError:
print("AttributeError: 'int' object has no attribute 'append'")
output.txt
AttributeError: 'int' object has no attribute 'append'
Summary
- Python raises different types of built-in exceptions for different error conditions.
- Always handle these exceptions using structured
try
/except
blocks. - Understanding common exceptions helps in writing robust, error-free applications.
Next, we will explore how to raise exceptions manually using raise
keyword — an important part of custom error handling in Python.