Recognize Common Exceptions
In this step, we will explore common exceptions. Unlike syntax errors, exceptions occur during program execution. The code is syntactically correct, but an error occurs while it is running.
The file common_exceptions.py is ready for you in the ~/project directory.
First, let's cause a ZeroDivisionError. Open common_exceptions.py in the editor and add the following code:
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
Save the file and run it from the terminal:
python common_exceptions.py
The program starts running but stops and displays a ZeroDivisionError. Mathematically, division by zero is undefined, and Python raises this exception to indicate the problem.
Traceback (most recent call last):
File "/home/labex/project/common_exceptions.py", line 3, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero
Next, let's trigger a NameError. This happens when you try to use a variable that has not been defined yet. Replace the content of common_exceptions.py with the following:
print(undefined_variable)
Save the file and run it:
python common_exceptions.py
You will get a NameError because the interpreter does not know what undefined_variable refers to.
Traceback (most recent call last):
File "/home/labex/project/common_exceptions.py", line 1, in <module>
print(undefined_variable)
NameError: name 'undefined_variable' is not defined
Now, let's see a TypeError. This occurs when you try to perform an operation on an object of an inappropriate type. Replace the content of common_exceptions.py with this code:
print("Hello" + 5)
Save and run the script:
python common_exceptions.py
You will see a TypeError. Python does not allow you to add (+) a string and an integer together directly.
Traceback (most recent call last):
File "/home/labex/project/common_exceptions.py", line 1, in <module>
print("Hello" + 5)
TypeError: can only concatenate str (not "int") to str
Finally, let's demonstrate an IndexError. This happens when you try to access an element of a sequence (like a list) using an index that is out of bounds. Replace the content of common_exceptions.py with the following:
my_list = [1, 2, 3]
print(my_list[5])
Save and run the script:
python common_exceptions.py
You will get an IndexError. The list my_list has three items, so its valid indices are 0, 1, and 2. Accessing index 5 is not possible.
Traceback (most recent call last):
File "/home/labex/project/common_exceptions.py", line 2, in <module>
print(my_list[5])
IndexError: list index out of range
Understanding these common exceptions is a key part of learning to debug Python code.