Adventures in Machine Learning

Mastering Python Exception Handling with ‘Finally’

Understanding Python Exception Handling with ‘finally’

Have you ever come across a situation where you needed to handle exceptions in your Python code? Exception handling is an essential part of programming, responsible for dealing with unexpected situations that can arise during code execution.

Python provides ‘try-except’ blocks for handling errors, but did you know that there is also a ‘finally’ keyword? In this article, we will explore what ‘finally’ does and its importance in ensuring code execution.

The Purpose and Usage of ‘finally’

The ‘finally’ keyword in Python allows you to execute a block of code regardless of whether an exception occurs or not. It serves as the final step in the ‘try-except’ block.

The use of ‘finally’ is not mandatory, but it’s essential in situations where you need to make sure that your code runs regardless of errors that may arise. Example of using ‘finally’:

In the following example, we attempt to divide a number by zero, which results in a ZeroDivisionError.

We’ll use a ‘try-except’ block to handle this exception and include a ‘finally’ block to execute code that must run regardless of the error. “`


result = 10 / 0

except ZeroDivisionError:

print(“Error: Division by zero”)



Finally block executed”)




Error: Division by zero

Finally block executed


As you can see from the output, the ‘finally’ block is executed even though the ‘except’ block handled the error that occurred. Importance of ‘finally’ in Ensuring Code Execution

The primary importance of ‘finally’ is to ensure that a piece of code is always executed, no matter what happens in the ‘try’ or ‘except’ blocks.

Execution of ‘finally’ Regardless of Exceptions:

One significant aspect of using ‘finally’ in Python is that it doesn’t matter whether an exception has occurred or not. ‘finally’ will be executed in either case.

Example illustrating how ‘finally’ ensures code execution:

Consider the following example where we have a file that we want to open, read data, and finally, close it. “`


file = open(‘example.txt’, ‘r’)

data =


except Exception as e:

print(f”Error: {e}”)



print(“File closed.”)


In this case, even if the ‘try’ block raises an exception, the file will be closed correctly in the ‘finally’ block.

It ensures that we avoid potential data loss or corruption.


Exception handling is an indispensable part of programming, allowing for the handling of unexpected situations that can arise during code execution. The ‘finally’ keyword in Python is an essential component of exception handling.

It ensures the execution of necessary code, regardless of whether an error occurs or not. By using ‘finally’ in your code, you can improve the overall stability and reliability of your program.

It’s a best practice that ensures all resources (including open files, database connections, and so on) are correctly released and prevents data loss or corruption. So next time you’re handling exceptions in your Python code, don’t forget to use the ‘finally’ keyword.

It could potentially save you a lot of headaches in the long run!

Python is a powerful programming language used widely for application development, machine learning, data analysis, and more. As a high-level language, it offers many features that simplify programming tasks, including an exception-handling framework for managing unforeseeable errors.

Python’s exception-handling capability through ‘try-except’ blocks provides a robust way to manage runtime errors. In addition, the ‘finally’ keyword provides an extra layer of protection that guarantees specific code blocks’ executions when exceptions occur.

In this article, we discussed the purpose, usage, and importance of ‘finally’ in Python exception handling. Summary of ‘finally’ Purpose and Usage

‘finally’ is a keyword in Python used to execute specific code blocks, even when an error or exception occurs.

Consider the following syntax:



# try-block code


# except-block code


# finally-block code


When we run code in a ‘try-except’ block, an error or exception might arise. In this case, the except-block executes and handles the error, but we risk a scenario where resources like files, databases, and network connections within the try-block are left open.

To avoid this issue, we use ‘finally,’ which is executed irrespective of whether an exception occurs or not. One of the major benefits of using ‘finally’ is that it ensures the resource handling that might have been left unhandled after an exception has been raised is done correctly.

The code block in ‘finally’ is where we can release resources like file handles, network sockets, and database connections. However, we can only use ‘finally’ with a ‘try-except’ block.

That is, it can’t be used alone. Importance of ‘finally’ in Ensuring Code Execution

The primary importance of ‘finally’ is to keep some critical code blocks or resources in good shape even when there are exceptions.

Suppose we have vital code that checks the database or performs a network operation. In that case, we do not want it to execute after an error occurs only when everything runs smoothly.

Consider an example of the following Python code:



# critical database code

# network operation

except Exception as e:

# Error handling code


print(“Final code”), # Close connections, etc


If there is an exception in the try-block, it is caught smoothly in the except-block, and we implement error handling. In some cases, we might end up with open database connections or leaking network sockets.

This is where the functionality of ‘finally’ comes into play. The code inside the ‘finally’ block executes after the try-except block, ensuring that database connections close and network sockets are released.

Therefore, it is essential to use ‘finally’ in our Python code to ensure that the resources used in our program are closed or disposed of whenever there is an error in our program. Best Practices in Using ‘finally’ in Python Exception Handling

Here are some of the best practices to follow when using ‘finally’ in your Python exception handling:


Always use ‘finally’ with a ‘try-except’ block. 2.

Use ‘finally’ to release resources before exiting a program. 3.

Write only essential code in the ‘finally’ block. 4.

Do not return a value in the ‘finally’ block. 5.

Avoid re-raising an exception in the ‘finally’ block. Example of Using ‘finally’ in a Python Program

Let’s consider an instance where we open a file, write some content to it, then close the file.

However, suppose we encounter an error while writing the file, leading to the except-block execution. In that case, we still need to close the file after executing the except block.

Here’s how we can handle that scenario using ‘finally’:





file = open(“example.txt”, “w”)

file.write(“Hello, World!”)

except Exception as e:

print(f”Error: {e}”)





In this code snippet, we create a file object and write ‘Hello World!’ to it. If there is an exception, it’s caught in the except block, and we print the error with the error message format.

The file.close() method performs a clean exit, closing the file object, and releasing the file resource.


In Python, handling exceptions using ‘try-except’ blocks is essential in protecting our program’s runtime from errors. By using a ‘finally’ block, we can ensure that critical code blocks or resources are always released even when an exception occurs.

By practicing the best practices for using ‘finally’ with ‘try-except’ blocks, we can maintain and improve the stability and reliability of our programs. Whenever we deal with critical resources like databases, files, and networks, we should utilize ‘finally’ to ensure that we handle them correctly and avoid resource leaks.

In conclusion, understanding how to handle exceptions in Python is crucial in ensuring our code’s reliability and stability. The ‘finally’ keyword plays a critical role in this process by allowing specific blocks of code to execute, irrespective of exceptions.

The importance of using ‘finally’ in code execution is evident in scenarios where critical resources like files, databases, and network connections are involved. By following best practices and using ‘finally’ in our Python exception-handling code, we can maintain stable programs and prevent resource leaking.

Consequently, it is vital to include ‘finally’ in our code to ensure that critical resources are closed or disposed of whenever there is an error in our program.

Popular Posts