Exceptions/Errors in Python
Python provides a robust exception-handling mechanism to deal with
runtime errors. Below are some common exceptions with examples:
1. IndexError: Occurs when trying to access an index in a sequence
that is out of range.
my_list = [1, 2, 3]
print(my_list[5]) # IndexError: list index out of range
2. KeyError: Occurs when trying to access a dictionary key that does
not exist.
my_dict = {"name": "John"}
print(my_dict["age"]) # KeyError: 'age'
3. NameError: Occurs when a variable is not defined before being
used.
print(x) # NameError: name 'x' is not defined
4. AttributeError: Occurs when trying to access an attribute that
does not exist in an object.
my_string = "Hello"
print(my_string.append(" World"))
# AttributeError: 'str' object has no attribute 'append'
5. ValueError: Occurs when an operation receives an argument of the
correct type but with an inappropriate value.
num = int("abc") # ValueError: invalid literal for int() with base 10:
'abc'
6. ZeroDivisionError: Occurs when dividing by zero.
print(10 / 0) # ZeroDivisionError: division by zero
7. FileNotFoundError: Occurs when attempting to open a non-
existent file.
with open("non_existent_file.txt", "r") as file:
content = [Link]() # FileNotFoundError: [Errno 2] No such file or
directory
8. ModuleNotFoundError: Occurs when trying to import a module
that is not installed.
import non_existent_module # ModuleNotFoundError: No module
named 'non_existent_module'
9. AssertionError: Occurs when an assert statement fails.
x=5
assert x > 10, "x is not greater than 10" # AssertionError: x is not
greater than 10
10. TypeError: Occurs when an operation is applied to an object
of an inappropriate type.
print("Hello" + 5) # TypeError: can only concatenate str (not "int")
to str