Sitemap

Python Exception Handling

5 min readMay 19, 2023

--

Before we dive into the main topic, it’s important to grasp the fundamentals of errors and exceptions and how they differ from each other. By briefly exploring these concepts, we can establish a better understanding and lay a solid groundwork for the upcoming discussion.

Press enter or click to view image in full size

Syntax Error

Syntax errors in Python arise when the code fails to compile with the prescribed rules and structure of the language. The Python interpreter identifies these errors during the parsing phase, which occurs prior to code execution. Common causes of syntax errors include misspelled keywords, omitted colons or parentheses, or incorrect indentation.

# Misspelled Keywords Example 
for i in range(5):
print(i)
if i == 3:
brak # ---> misspelled keyword here

# Incorrect Indentation Example
num = 10
if num > 0:
print("Positive number") # ---> Intend error

for i in range(3):
print(i) # ---> Intend error

Exceptions

Exceptions refer to errors that occur while a program is running. These errors can occur for various reasons, such as dividing a number by zero, accessing an index beyond the range of a list, or trying to open a non-existent file. Exceptions have the potential to disrupt the program’s regular execution and lead to termination if not appropriately managed.

# Exception Error: IndexError
my_list = [11,22,33,44,55,66,77]
print(my_list[10])


#------OUTPUT--------#

Traceback (most recent call last):
File "<string>", line 3, in <module>
ERROR!
IndexError: list index out of range

try and except

Exceptions are errors that occur during the execution of a program and can disrupt its normal flow. By using try-except, you can catch and gracefully handle these exceptions, preventing your program from crashing.In Python, the try-except statement is a powerful tool used to handle exceptions.

Press enter or click to view image in full size

try block: This is the section where you put the code that might cause errors or exceptions. It acts as a monitoring area for potential issues.

except block: When an exception is raised within the try block, the program immediately jumps to the corresponding except block. Here, you can define how to deal with specific types of exceptions, like displaying error messages or implementing alternative actions.

else block: If no exceptions occur in the try block, the code within the else block is executed. It provides a way to specify actions that should only run when the code in the try block successfully executes without any exceptions. It is helpful for executing additional steps when everything goes smoothly.

Here’s an example of how to use a try-except-else block to handle the IndexError Exception.

# Exception Error: IndexError
my_list = [1, 2, 3]
try:
print(my_list[5])
except IndexError:
print("Index out of range. Please provide a valid index.")
else:
print("Index accessed successfully.")

#------OUTPUT--------#

Index out of range. Please provide a valid index.

The above code within the try block attempts to access an element at index 5 in the my_list. Since this index is out of range and will raise an IndexError exception, it is caught by the except block. The program then executes the code within the except block, printing an error message.

Get Prakash Ramu’s stories in your inbox

Join Medium for free to get updates from this writer.

If no exception is raised within the try block, the code within the else block is executed, indicating that the index was accessed successfully. In this case, it will print the message "Index accessed successfully."

finally keyword

The finally block can be used in conjunction with the try-except-else block to specify a block of code that should always be executed, regardless of whether an exception is raised or not.

my_list = [11,22,33,44,55,66,77]
try:
print(my_list[10])
except IndexError:
print("Index out of range. Please provide a valid index.")
else:
print("Index accessed successfully.")
finally:
print("This code will always run.")

#------OUTPUT--------#

Index out of range. Please provide a valid index.
This code will always run.
>

After the except block, the finally block is introduced. It always executes its code, regardless of exceptions.

If an IndexError exception occurs, the program enters the except block, prints the error message, and proceeds to the finally block, which prints “This code will always run.”

If no exception occurs, the else block executes, indicating a successful index access. Then, the program proceeds to the finally block, ensuring its code always executes. The finally block is commonly used for cleanup operations or actions that must be performed regardless of exceptions, like closing files, releasing resources, or logging.

raise and Exception Object

We can manually raises an exception using raise keyword. The raise keyword triggers a particular exception when certain conditions are met or errors occur. The raised exception can be either an instance or a class. By using the raise keyword, you have the ability to specify the type of error that should be raised for a specific exception.

def divide_numbers(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero, It was a manually raised error ")
else:
return a / b

An Exception object comes into existence when a program encounters an error or an exceptional situation during its execution. It contains details about the error, aiding in the identification and resolution of the issue at hand. When an exception is raised, Python automatically generates an exception object.

Picture an exception object as a container that holds crucial information regarding the error, including the error type and a description elucidating the nature of the problem.

For instance, you can retrieve the error message or log the error for effective debugging.

def divide_numbers(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
else:
return a / b

try:
result = divide_numbers(10, 0)
print(result)
except ZeroDivisionError as error:
print(error)


#------OUTPUT--------#
Cannot divide by zero

The above code defines a function called divide_numbers that takes two arguments, a and b. Inside the function, it checks if b is equal to zero. If it is, it raises a ZeroDivisionError exception with the error message "Cannot divide by zero". Otherwise, it performs the division operation a/b and returns the result.

In the try block, the function divide_numbers is called with arguments 10 and 0, which raises a ZeroDivition exception. Since an exception is raised, the program jumps to the except block where the exception object is assigned to the variable error . The print statement in the except block prints the error message associated with the exception.

Hopefully, this article has provided you with a comprehensive understanding of the fundamental mechanisms that Python provides for handling exceptions. It is our aim that through this discussion, you have gained valuable insights into the essential techniques and tools available in Python for effectively managing and responding to exceptional situations. By familiarizing yourself with these concepts, you are now equipped with the necessary knowledge to confidently address and handle exceptions in your Python programs.

--

--