In this article, we will learn about errors and exceptions in the Python language. The main difference is errors are simply syntax errors that occur before the program is executed and exception is a runtime error that occurs during the execution of the program. Simple right? Let's deep dive now.
Errors
Syntax in a programming language is nothing but meaning. The way you are supposed to write a programming language is syntax and if that is violated, the Python interpreter will immediately tell you that this is not the way to write a Python program giving you a SyntaxError.
if x = 3:
print('Python is super')
The above code snippet throws SyntaxError as we have used an assignment operator in the if condition. Because x = 3 does not return any value and if keyword expects a boolean value.
Note: In C language x = 3 returns the value of the variable that is 3 which is interpreted as True, hence not a problem unlike in Python
The two types of SyntaxError are IndentationError (Python syntax depends heavily on indentation and hence improper indentation leads to an error) and TabError (when tabs and spaces are used together inconsistently to provide indentation).
Note: Semantic errors will run without producing error messages but the output will be wrong. For example, while writing a program if we do not take care of the precedence of operators like:
6 / 2 / 4 # same as 3 / 4 = 0.75
# you might be expecting the result 12.0, but forgetting the brackets will
# lead to semantic error as in this case. It can resolved by,
6 / (2 / 4) # same as 6 / 0.5 = 12.0
# here / operator operates from left to right, hence without brackets it
# evaluates 6 / 2 first and then the result is divided by 4
Exceptions
In case of exceptions, we have several types and it will be really convenient if you know eight of them. Fortunately, the names of these errors are self-explanatory. Before reading the explanation, I highly recommend you guess what kind of error is each of them.
NameError
sum = a + 5 # NameError
If you use a variable like 'a' in the code snippet without defining it, you will get NameError.
The correct form of the code can be:
a = 4 sum = a + 5
ZeroDivisionError
As the name suggests, division by zero is not defined mathematically.
x = 0 y = 10 result = y % x # ZeroDivisionError result = y / x # ZeroDivisionError result = y // x # ZeroDivisionError
TypeError
Though Python is a dynamically typed language, we cannot apply operation or function to any type. For example:
# Arithmetic Operations
result = "cat" + 23 # TypeError: can only concatenate str (not "int") to str
result = "cat" - 52 # TypeError: unsupported operand type(s) for -: 'str' and 'int'
# Function Call
length = len(56) # TypeError: object of type 'int' has no len()
# len() function can take string, list, tuple, set, dictionary but not int
# Iterating Over Non-Iterable Types
for char in 23: # TypeError: 'int' object is not iterable
pass
ValueError
Here, an operation or a function is applied to a correct type but invalid value.
# Invalid Input Format result = int('2.4') # int() function takes only a valid integer string result = int('air') sqrt_value = math.sqrt(-1) # ValueError: math domain error
In the code snippet, string type is allowed to pass in the int() function but the value should be a valid integer like int('2') will work that converts the string 2 to integer 2, and int(3.45) will convert the float 3.45 to integer 3.
FileNotFoundError
with open('non_existent_file.txt', 'r') as file: content = file.read() # This will raise a FileNotFoundError
IndexError
We find the index in a string, list, and other iterable in Python. Hence when we try to access the index of the iterable outside its range, we get IndexError.
lst = [1, 2, 3] lst[10] # IndexError: list index out of range
KeyError
Where do we have keys in Python? In the dictionary of course. When we try to access the key that does not exist. Alternatively, we can use the get() method that returns None instead of throwing an error if the key is not found.
my_dict = {'name': 'Alice', 'age': 25} value = my_dict['gender'] # KeyError: 'gender' my_dict.get('gender') # returns None
SystemExit
SystemExit is an exception in Python that is raised when the sys.exit() function is called. It is a subclass of the BaseException class and is used to exit the Python interpreter or terminate the current script.
The sys.exit() function allows you to gracefully exit a Python program. When this function is called, the program will stop executing immediately, and any cleanup code or operations that should be performed before exiting may not be executed.
import sys
def main():
user_input = input("Do you want to exit? (yes/no): ")
if user_input.lower() == 'yes':
print("Exiting...")
sys.exit() # This will exit the program
print("Continuing with the program.")
if __name__ == "__main__":
main()
The program prompts the user to input whether they want to exit. If the user's input is "yes," the sys.exit()
function is called, causing the program to exit immediately. If the user's input is "no," the program continues.
The exceptions will occur only when you run your program and hence you should be very careful about exceptions. In the case of syntax errors, the Python interpreter will not allow you to continue until you correct them but exceptions can occur anywhere and anytime. We can't use the if condition to avoid every possible exception hence there is an elegant way to escape exceptions and to keep the program workflow very smooth. We will learn this in the next part.